Ok, I finally got this damn thing work! :)
下面是整个代码,很难解释,就将就着用把:
DLL:
CString FunSys(int* p, CString str);
C#:
[StructLayout(LayoutKind.Sequential)]
public struct MyString {
public IntPtr _str;
}
[DllImport("mydll.dll", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)]
public extern static void DllFun(IntPtr pt, ref int i, string str);
//千万别问我为什么:)
调用:
int i = 0;
IntPtr mem = Marshal.AllocHGlobal(64); //申请多点内存,先。
DllFun(mem, ref i, "hello, world");
MyString mystr = (MyString)Marshal.PtrToStructure(mem, typeof(MyString));
string str = Marshal.PtrToStringAnsi(mystr._str);
Console.WriteLine(str);
Marshal.FreeHGlobal(mem);
...
我的代码是这样写的,执行的时候总是报错。
请指教,谢谢!
------------
An unhandled exception of type 'System.NullReferenceException' occurred in CallAPI2.exe
Additional information: Object reference not set to an instance of an object.
------------
源代码:
private void button1_Click(object sender, System.EventArgs e)
{
string a="aaa";
string strResult="";
int i=0;
strResult = FunSys(ref i, a);
}
[DllImport("DllName.dll",CharSet=CharSet.Auto)]
public static extern string FunSys(
ref int para1,
string para2
);