[问题] 在C#使用C++物件遇到的问题

楼主: Dong0129 (阿东跟上面讲的情况一样b)   2023-11-27 16:29:11
最近在开发将客户提供的资源打包成供自家C#使用的DLL档,
但执行到某个函式会出现错误,错误如下,
"0x00007FFE66AE1CEC (UniversalUS.dll) 中 (于 Sample.exe)
掷回例外状况: 0xC0000005: 读取位置 0x0000000000000064 时发生存取违规。"
想问问是否我的写法有误..
范例档案如下,
客户提供的资源以3rd.h和3rd.dll表示。
Test.h档案内容如下,
include "3rd.h"
class __declspec(dllexport) Test
{
private:
//define in 3rd.h
3rdTest* 3rdtest;
public:
Test(){
HINSTANCE hDll=LoadLibrary("3rd.dll");
typeof int(*CreateObj)(3rdTest** p3rdTest)
CreateObj createObj=(CreateObj)GetProcAddress((HMODULE)hDll,"l
pP
createObj(&3rdtest);
}
~Test()
{
3retest.Release();
}
int GetOtherObj(OtherObj** obj)
{
return 3rdtest->GetOtherObj(obj);
}
}
ExternTest.h如下
#include "Test.h"
extern "C"
{
extern __declspec(dllexport) Test* CreateTest();
extern __declspec(dllexport) void DisposeTest(Test* pTest);
extern __declspec(dllexport) int GetOtherObj(Test* test);
}
Test.cpp如下
#include "ExternTest.h"
extern "C"
__declspec(dllexport) Test* CreateTest()
{
return new Test();
}
extern "C"
__declspec(dllexport) void DisposeTest(Test* pTest)
{
pTest->~Test();
}
extern "C"
__declspec(dllexport) OtherObj* GetOtnerObj(Test* pTest)
{
OtherObj* otherObj;
pTest->GetOtherObj(&otherObj);
return otherObj;
}
在C#内使用状况如下,
ShTest.cs
public class ShTest:IDisposable
{
#region dllimport
[DllImport("Test.dll")]
private static extern IntPtr CreateTest();
[DllImport("Test.dll")]
private static extern void DisposeTest(IntPtr pTest);
[DllImport("Test.dll")]
private static extern IntPtr GetOtherObj(IntPtr pTest);
#endregion
#region ShapeFunction
IntPtr pTest;
public ShTest()
{
pTest=CreateTest();
}
public void Dispose()
{
DisposeTest(pTest);
}
public ShOtherObj GetOtherObj()
{
IntPtr pOtherObj=GetOtherObj(pTest);
return new ShOtherObj(pOtherObj);
}
#endregion
}
执行到IntPtr pOtherObj=GetOtherObj(pTest);时会跳出存取违规的错误讯息,请问是否
我的写法有错误呢?
作者: NDark (溺于黑暗)   2023-11-27 17:22:00
GetOtnerObj 这有TYPO吗?3retest.Release(); 这有TYPO吗?return 3rdtest->GetOtherObj(obj); 这行要确认一下3rdtest 可能没有正确生成3rdtest->GetOtherObj() 呼叫下去 就看不到了
作者: wulouise (在线上!=在电脑前)   2023-11-27 21:53:00
GetProcAddr好像没写完整少括号OtherObj* GetOtnerObj(Test* pTest)是不是打错?

Links booklink

Contact Us: admin [ a t ] ucptt.com