(1)C语言产生DLL代码如下,产生csharptest.dll:
*********************1**************************
/*
* str [in/out]
* file [in/out]
*/
int TestStr(char* str, char *file)
{
struct MyStruct{
int num;
char str1[4];
char str2[12];
};
/*对第一个参数(某结构类型)赋值*/
struct MyStruct me;
me.num = 100;
strcpy(me.str1, "AAA");
strcpy(me.str2, "1234567890a");
memcpy(str, &me, sizeof(struct a));
/*对第二个参数赋值*/
strcpy(file, "111111111");
return 0;
}
********************1***************************
(2).net中调用DLL方法如下,Class1.cs:
********************2***************************
using System;
using TongTech.Interface;
using System.Runtime.InteropServices;
using System.Text;
namespace cmfp_cli
{
unsafe class Class1 /*使用unsafe类、结构及方法*/
{
static int ret = 5;
/*对应于struct MyStruct*/
public unsafe struct MyStruct
{
public int num;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 4)]
public string str1;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 12)]
public string str2;
}
/*声明:第一个参数为不固定的结构类型,第二个参数为一个字符串*/
[DllImport("csharptest")]
static extern int TestStr(void* voidStr, StringBuilder file);
unsafe static void Main()
{
IntPtr test;
MyStruct p = new MyStruct();
test = Marshal.AllocHGlobal(1024);
/*对于输入、输出char*类型,在.net中,用StringBuilder进行类型对应*/
StringBuilder file = new StringBuilder(100);
TestStr( test.ToPointer(), file);
p = (MyStruct)Marshal.PtrToStructure(test, typeof(MyStruct));
Console.WriteLine("====== p.num.ToString() ======" + p.num);
Console.WriteLine("====== p.str1.ToString() ======" + p.str1);
Console.WriteLine("====== p.str2.ToString() ======" + p.str2);
Console.WriteLine("====== file.ToString() ======" + file);
}
}
}
*********************2*************************
运行结果如下:
====== p.num.ToString() ======100
====== p.str1.ToString() ======AAA
====== p.str2.ToString() ======1234567890a
====== file.ToString() ======111111111
(3)注意:
使用unsafe方法时,需要在csharp工程中,进行如下设置
【项目】-》【属性】-》【生成】-》【允许不安全代码】处,打勾