我有这个简单的代码:
typedef void (__stdcall * OrdersCallback)(ordersTest*);
__declspec(dllexport) void InitializeCallbacks(long ordersCallbackAddress_) {
OrdersCallback ordersCallbackFunction;
std::cout << "current ordersCallbackFunction = " << ordersCallbackFunction << " address = " << &ordersCallbackFunction << std::endl;
std::cout << "set ordersCallbackAddress_ = " << ordersCallbackAddress_ << std::endl;
ordersCallbackFunction = (OrdersCallback) ordersCallbackAddress_;
std::cout << "new ordersCallbackFunction = " << ordersCallbackFunction << " address = " << &ordersCallbackFunction << std::endl;
ordersTest test;
test.replID = 123;
std::cout << "use ordersCallbackFunction = " << ordersCallbackFunction << " address = " << &ordersCallbackFunction << std::endl;
ordersCallbackFunction(&test);
}
当回调调用 AccessViolationException 时:
current ordersCallbackFunction = 000007F92BC354E0 address = 0000009785D1EC68
set ordersCallbackAddress_ = -2043003524
new ordersCallbackFunction = FFFFFFFF863A3D7C address = 0000009785D1EC68
use ordersCallbackFunction = FFFFFFFF863A3D7C address = 0000009785D1EC68
Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
我不明白出了什么问题,在另一个项目中非常相似的代码可以工作。谢谢!
更新,更多代码:
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate void OrdersCallback(ref OrdersTest value);
[DllImport("CGateNativeAdapter.dll"), SuppressUnmanagedCodeSecurity]
public static extern void InitializeCallbacks(
[MarshalAs(UnmanagedType.FunctionPtr)] OrdersCallback ordersSnapshotCallbackPointer);
OrdersCallback ordersCallback =
delegate(ref OrdersTest value)
{
Console.WriteLine("C# Orders call received = " +
" replID = " + value.replID);
};
InitializeCallbacks(ordersCallback);