C#学习经验(一)
上个星期编了一个C#的小程序,遇到的第一个问题就是如何利用以前用C++实现的现成DLL程序。
由于该DLL(decrypt.dll)只包含了两个运算函数,不能在C#中用引用的方式直接加入。
查了一些这方面的资料,解决如下:
这两个函数原先的定义如下:(输入的参数为字符串指针)
int GetTD(char*, char*);
int GetDP(char*, char*, int)
1、由于C#中没有脱离类之外的函数,首先在C#代码中,建立如下类:(包括两个静态的方法成员)
public class RefComm
{
[DllImport("decrypt.dll", EntryPoint = "GetTD", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern int GetTD(string a, string b);

[DllImport("decrypt.dll", EntryPoint = "GetDP", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern int GetDP(string a, string b, int c);
}
2、这两个方法被定义成静态的,在程序其它部份就可以直接使用了
dl1 = RefComm.GetTS(l1, l2);
dl2 = RefComm.GetDM(l1, l2, FX);
总结:
1、需要使用using System.Runtime.InteropServices;的命名空间。
2、C#中不建议使用指针,因此传递参数相应为string类型。
3、字符类型要设为CharSet.Ansi,设为CharSet.Auto会产生乱码。
由于该DLL(decrypt.dll)只包含了两个运算函数,不能在C#中用引用的方式直接加入。
查了一些这方面的资料,解决如下:
这两个函数原先的定义如下:(输入的参数为字符串指针)
int GetTD(char*, char*);
int GetDP(char*, char*, int)1、由于C#中没有脱离类之外的函数,首先在C#代码中,建立如下类:(包括两个静态的方法成员)
public class RefComm
{
[DllImport("decrypt.dll", EntryPoint = "GetTD", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern int GetTD(string a, string b);
[DllImport("decrypt.dll", EntryPoint = "GetDP", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern int GetDP(string a, string b, int c);
}
dl1 = RefComm.GetTS(l1, l2);
dl2 = RefComm.GetDM(l1, l2, FX);1、需要使用using System.Runtime.InteropServices;的命名空间。
2、C#中不建议使用指针,因此传递参数相应为string类型。
3、字符类型要设为CharSet.Ansi,设为CharSet.Auto会产生乱码。

浙公网安备 33010602011771号