代码改变世界

c#调用c++写成的dll文件,返回char*,返回数组,用ref接收,byte[]

2008-06-02 18:07  Virus-BeautyCode  阅读(12924)  评论(0编辑  收藏  举报


// Inclusion guard
#ifndef _DLLTUT_DLL_H_
#define _DLLTUT_DLL_H_

// Make our life easier, if DLL_EXPORT is defined in a file then DECLDIR will do an export
// If it is not defined DECLDIR will do an import

#if defined DLL_EXPORT
#define DECLDIR __declspec(dllexport)
#else
#define DECLDIR __declspec(dllimport)
#endif

// Specify "C" linkage to get rid of C++ name mangeling
extern "C"
{
    
// Declare 2 functions
    DECLDIR int Add( int a, int b );
    DECLDIR 
void Function( void );
    DECLDIR 
void GetPrt( char * prtStr );
}


// End the inclusion guard
#endif


起因是,我想让c++的同事给我一个读取硬件编号的函数,没有参数,返回值是编号,可是我的同事说返回string不规范,返回结果应该是true或者false,然后利用参数返回值,就是利用指针返回编号,他就写了一个方法,我找了一些方法试验了一下,下面这种可行,希望给大家一点提示吧。


using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace ConsoleApplication30
{
    
class Program
    
{
        
static void Main(string[] args)
        
{
            test.Function();

            Console.WriteLine(
"result: " + test.Add(23).ToString());

            
//string str = "aaddddddddddd";
            byte[] str = new byte[12];

            test.GetPrt(
ref str[0]);

            Console.WriteLine(System.Text.Encoding.GetEncoding(
"GB2312").GetString(str));

            Console.ReadLine();
        }

    }

    
class test
    
{
        [DllImport(
"..\\..\\lib\\DLLTest.dll")]
        
public static extern  void Function(); 

        [DllImport(
"..\\..\\lib\\DllTest.dll")]
        
public static extern int Add(int i,int j);

        [DllImport(
"..\\..\\lib\\DllTest.dll")]
        
public static extern void GetPrt(ref byte prtStr);
    }

}

 

记录一些有用的链接吧

http://www.cnblogs.com/wantfei/archive/2004/06/16/16194.html

http://www.cnblogs.com/wy/articles/123656.html

 http://dotnet.csdn.net/page/aab1def7-35a4-4a5f-bd18-c82879278b22

http://www.liuwu.net/post/how-to-passing-structures-and-classes-to-unmanaged-code.aspx

http://www.cnblogs.com/oceanlzhang/archive/2007/09/18/897698.html

http://www.blue1000.com/bkhtml/2007-12/55484.htm

http://www.cnblogs.com/songwin/articles/1329545.html


最近老是碰到问题啊,提示“无法加载 DLL“FUKeyDll.dll”: 找不到指定的模块。 (异常来自 HRESULT:0x8007007E)。”,

 

这个问题也被解决了,多半是因为FUKeyDll.dll调用了其他的dll文件,缺少了其他的dll文件