C++;从C#应用程序调用函数。试图读取或写入受保护内存错误 我试图从C++控制台应用程序调用C++函数。 这里是C++函数 extern int mpsCheck(mpsHandlePtr handle);

C++;从C#应用程序调用函数。试图读取或写入受保护内存错误 我试图从C++控制台应用程序调用C++函数。 这里是C++函数 extern int mpsCheck(mpsHandlePtr handle);,c#,c++,pinvoke,C#,C++,Pinvoke,其中,mpsHandlePtr定义为 typedef struct mpsHandleRec *mpsHandlePtr; 在我的C#中,我使用了以下语法 [DllImport("test.dll", EntryPoint = "mpsCheck", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)] public static extern int mpsCheck(ref System.IntPtr

其中,mpsHandlePtr定义为

typedef struct  mpsHandleRec *mpsHandlePtr;
在我的C#中,我使用了以下语法

[DllImport("test.dll", EntryPoint = "mpsCheck", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
public static extern int mpsCheck(ref System.IntPtr handle);
调用函数时,我遇到以下错误: 试图读取或写入受保护内存错误

非常感谢您的帮助


谢谢

您需要在C#中声明结构,然后将其传递给函数。像这样:

[StructLayout(LayoutKind.Sequential)]
struct mpsHandleRec 
{
     // fields go here
}

[DllImport("test.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int mpsCheck(ref mpsHandleRec handle);
或者,如果只有指向结构的不透明指针,则忽略结构声明并传递不透明指针:

[DllImport("test.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int mpsCheck(IntPtr handle);

否,如果将
IntPtr
作为指针传递,请不要使用
ref
。仅当您直接传递结构时才使用
ref
。谢谢您的回答。事实上,我在没有声明ref的情况下尝试了,但仍然得到了相同的错误:尝试读取或写入受保护内存错误[DllImport(“test.dll”,CallingConvention=CallingConvention.Cdecl)]公共静态外部int-mpsCheck(IntPtr句柄);