很奇怪的事情,C#调用C++写好的dll。在两边均已定义好结构体,通过ref进行传值。值可以传出来,但是始终报错:Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
C++端代码如下:
extern "C" _declspec(dllexport) void TestFun(TestStrct *strct);
typedef struct
{
wchar_t *a;
//char* a;
} TestStrct;
void TestFun(TestStrct *strct)
{
strct->a = AnsiToUnicode("asdasd");
//strct->a = "asdasd";
}
C#端代码如下:
[DllImport(@"lib\DiacomTest.dll", CharSet = CharSet.Ansi, EntryPoint = "TestFun", CallingConvention = CallingConvention.Cdecl)]
public static extern void TestFun(ref TestStrct strct);
void iniFun()
{
TestStrct strct = new TestStrct();
strct.a = "111"; //这一步传送进去没有问题
TestFun(ref strct); //这一步永恒报错,但是值可以传出来
Console.WriteLine(strct.a);
}
[StructLayoutAttribute(LayoutKind.Sequential)]
public struct TestStrct
{
/// WCHAR*
[MarshalAsAttribute(UnmanagedType.LPWStr, SizeConst = 20)]
public string a;
}
在线等,谢谢大侠
------解决思路----------------------
酱紫,
1. C++这边TestFunc改成酱:
extern "C" __declspec(dllexport) TestStrct* TestFunc(char* a)
{
TestStrct* strct= (TestStrct*)malloc(sizeof(TestStrct));
strcpy(strct->a, a);
return strct;
}
2.C#这边改成酱:
IntPtr ptr = TestFunc("abcd“);
TestStrct strct= (TestStrct )Marshal.PtrToStructure(ptr, typeof(TestStrct ));
试一下,我没试过,但感觉这样就没问题了