如何使用C# 调用c语言写的dll

1引用命名空间:

usingSystem.Runtime.InteropServices;

2.将需要调用的dll放到bin文件工程目录下,程序编译运行时会将该dll复制到bin文件debug文件夹下;

3.使用dllimport引用需要的函数

[DllImport("Test.dll",CharSet=CharSet.Auto,CallingConvention=CallingConvention.StdCall)]publicstaticexternvoidTest123(byte[]input,intport);

函数原型如下:

void__stdcallTest123(constchar*input,constintport);

说明:CallingConvention 选择调用类型,取决于你写的C函数的调用类型,一般情况都会使用stdcall。

涉及到的数据类型需要认真对比下,网上有大神把能想到的都试了一遍,可以认真看下。以下变量是我使用过的,可以参考下

int& variable ----> ref int variable

char * out_variable ----> [MarshalAs(UnmanagedType.LPStr)] StringBuilder out_variable

const char * In_varible ----> byte[] // byte[] bytes = System.Text.Encoding.Default.GetBytes(In_varible);

4.其他:

调试过程出现了“buffer too small ”的问题,

刚初始化的使用的是StringBuilder ss = new StringBuilder();

后修改为StringBuilder ss = new StringBuilder(1024),问题解决

生成release版时,出现了找不到dll的问题,

解决方法,手动将dll复制到release文件夹下,问题解决