我正在将 c++ 函数从 dll 导入到我的 winform c# 应用程序:
[DllImport(@"eyeWhere.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
public static extern int Eye_GetPositionS(string filename, [MarshalAs(UnmanagedType.LPArray, SizeConst = 9)] double[] sensors);
当我从构造函数中调用该函数时,它工作正常。
问题是当我从
中打开的新线程调用它时
“fleck websocket 服务器”Fleck , "onMessage" Action ,
然后它抛出“system.access.violation”异常。
我设法将问题缩小到我传递的双数组, 似乎指向它的指针已损坏。
我找不到问题的根源,一件事是确保 dll 中的功能在我测试时正常工作。
函数调用(两个阶段):
- 在“fleck”中打开新线程:
socket.OnMessage = message =>
{Thread locationThread = new Thread( unused => processLocation(fileName,socket,sensorsList,sensors) );
locationThread.Start();}
- 实际功能:
private void processLocation(string fileName, IWebSocketConnection sock, List<Sensor> sensorsList, double[] sensors)
{
int map_position = Eye_GetPositionS(fileName,sensors);<br/>
string locationString = "floor:1,mx:" + (map_position / 10000) + ",my:" + (map_position % 10000);
// send location string to user
sock.Send(LOCATION_CODE + "-" + locationString);}
界面是:
extern "C" __declspec(dllexport) int Eye_GetPositionS(const wchar_t *fname_mob, double sensors[9], int &map_x, int &map_y)
我没有像编写 dll 的人所同意的那样传递最后两个参数 (int&)。
最佳答案
I am not passing the two last arguments (
int&
) as agreed with the man who wrote the DLL.
嗯,问题来了。您不能省略参数。应该是:
[DllImport(@"eyeWhere.dll", CallingConvention = CallingConvention.Cdecl,
CharSet = CharSet.Unicode)]
public static extern int Eye_GetPositionS(
string filename,
[In, MarshalAs(UnmanagedType.LPArray, SizeConst = 9)]
double[] sensors,
ref int map_x,
ref int map_y
);
无论编写 DLL 的人怎么说,您都不能忽略这些参数。也许他的意思是参数真的是int*
,你可以传递nullptr
。
我为这些参数使用了 ref
,但也许它们应该被 out
。您大概知道哪个是合适的。
同样,我在猜测 sensors
参数的意图。如果数据流出而不是流入,则使用Out
。如果数据双向流动,请使用 [In, Out, ...]
。
关于c# - 从 c# 中的线程调用 c++ 函数时出现 system.access.violation 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28330422/