当前位置: 代码迷 >> VC >> C#调用C++的dll 指向结构体指针的指针有关问题
  详细解决方案

C#调用C++的dll 指向结构体指针的指针有关问题

热度:4821   发布时间:2013-02-25 00:00:00.0
C#调用C++的dll 指向结构体指针的指针问题
C++代码
typedef struct _LSHSearchResultT{
int distance;
string framefile;

} LSHSearchResultT, *PLSHSearchResultT;

extern "C" DLL_EXPORT int RNN(LSHSearchResultT **lshresult);

C#代码
public struct LSHSearchResultT
{
  public int distance;
  public string framefile;
   
};

public static extern int RNN(out IntPtr lshresult);

使用时,
IntPtr lshresult;
int sum = test.RNN(out lshresult);
LSHSearchResultT[] lsh = new LSHSearchResultT[2];
for (int i = 0; i < 2; i++)
{
  IntPtr ptr = Marshal.ReadIntPtr(lshresult, i * 4);
  lsh[i] = (LSHSearchResultT)Marshal.PtrToStructure(ptr, typeof(LSHSearchResultT));
//运行到此处:提示尝试读取或写入受保护的内存,这通常指示其他内存已损坏
}

为什么啊?谢谢

------解决方案--------------------------------------------------------
C++结构中不能包含类对象(string)。
------解决方案--------------------------------------------------------
我晕,string是C++的吗?把它换成char string[255];

extern "C" DLL_EXPORT int RNN(LSHSearchResultT **lshresult); 
换成:
extern "C" DLL_EXPORT int RNN(LSHSearchResultT &lshresult); 

public struct LSHSearchResultT 

public int distance; 
public string framefile; 

}; 
改成:
public struct LSHSearchResultT 

public int distance; 
public char[] framefile=new string[255]; 

}; 

public static extern int RNN(out IntPtr lshresult); 
改成:
public static extern int RNN(ref LSHSearchResultT lshresult); 

下面都要相应改动,我就省略了。
  相关解决方案