[英]system.access.violation exception while calling c++ function from a thread in c#
我正在将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”操作,
然后会引发“ system.access.violation”异常。
我设法将问题缩小到我要传递的双精度数组,似乎指向它的指针已损坏。
我找不到问题的根源,一件事是确定dll中的功能在我测试时是否正常工作。
函数调用(两个阶段):
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);
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&)。
我没有传递与编写DLL的人相同的最后两个参数(
int&
)。
好吧,这里有问题。 您不能忽略参数。 它应该是:
[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, ...]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.