我有一个旧的 C++ 函数,我必须在我的 .NET 应用程序中使用它。每次我尝试调用并将指针转换回类时,我都会收到一条错误消息,指出我试图读取或写入 protected 内存。请有人帮我指出正确的方向。这是代码:
typedef struct
{
char szModel[32];
float fSpeed;
float fData[20];
} CAR, far *LP_CAR;
//Function prototype
int FAR PASCAL Process(char szModel[32], LP_DATA pCar);
还有我的 .NET 代码:
[DllImport("Unmanaged.dll", CharSet = CharSet.Ansi)]
public static extern int Process(string model, IntPtr data);
//****** Implementation **********
public class ManagedClass
{
public string szModel = new string(new char[32]);
public float fSpeed;
public float[] fData = new float[20];
}
ManagedClass aCar = new ManagedClass();
IntPtr ptr = Marshal.AllocHGlobal(Marshal.Sizeof(aCar));
Marshal.StructureToPtr(aCar, ptr, false);
Process(aCar, ptr);
ManagedClass model2 = (ManagedClass)Marshal.PtrToStructure(ptr,
typeof(ManagedClass));
最佳答案
我会这样做:
C++
typedef struct
{
char szModel[32];
float fSpeed;
float fData[20];
} CAR, far *LP_CAR;
extern "C" {
int __stdcall Process(char *szModel, CAR &lpCar);
}
C#
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
struct CAR
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string szModel;
float fSpeed;
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 20)]
float[] fData;
}
[DllImport("Unmanaged.dll", CharSet = CharSet.Ansi)]
static extern int Process(
string model,
ref CAR data
);
调用如下:
CAR data;
Process(@"test", ref data);
关于.net - 从 .NET 为非原始数据类型调用旧的 C++ 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5407424/