拙网论坛

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 191|回复: 0

C++/CLI wrapper for native C++ dll

[复制链接]

949

主题

1001

帖子

3736

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
3736
发表于 2018-10-12 01:26:50 | 显示全部楼层 |阅读模式
I have written an C++/Cli wrapper for a native C++ dll, but when I call some method from C# I get an System.AccessViolationException error in my C++/Cli Wrapper dll! It's necessary to marshal the unmanaged types or something else?!
// Wrapper.htypedef UnmanagedClass* (*Instance)(void);private:    UnmanagedClass *m_object; // unmanaged object   // Wrapper.cppWrapper:Wrapper(){    HINSTANCE unmanagedLib;    unmangedLib = LoadLibrary(SystemStringToLPCSTR(dllPath+dllName));    // load instance    Instance _createInstance = (Instance)GetProcAddress(unmangedLib, "GetInstance");    m_object = (_createInstance)(); }Wrapper::~Wrapper(){    m_object->~UnmanagedClass();}Uint32 Wrapper::SomeMethod(Uint8 *bytRecvBuffer, int &iRecvLen){    return m_object->SomeMethod(bytRecvBuffer, iRecvLen);}// Unmanaged Classclass UnmanagedClass    {public:    /**    * Default constructor.     */    UnmanagedClass(void);    /**    * Default Destructor    */    ~UnmanagedClass(void);    virtual Uint32 Wrapper::SomeMethod(Uint8 *bytRecvBuffer, int &iRecvLen);};// export the UnmanagedClass objectextern "C" _declspec(dllexport) UnmanagedClass* GetInstance();// UnamangedClass.cppUnamangedClass::~UnamangedClass(void){    if (UnamangedClassDLL != NULL)        FreeLibrary(UnamangedClassDLL);    UnamangedClassDLL = NULL;}extern "C" _declspec(dllexport) UnmanagedClass* GetInstance(){    return new UnmanagedClass();}
When I call at example SomeMethod from C# I get the error in C++/Cli dll! (I included the C++/cli dll with add reference in C sharp project and create the Wrapper object)
Thank you for your help!
greets
https://stackoverflow.com/questions/6135391/c-cli-wrapper-for-native-c-dll#
--------------------

It is inappropriate to directly call the destructor of an object that was allocated with (non-placement) new. Try changing
m_object->~UnmanagedClass();
to
delete m_object;m_object = 0;
(m_object = 0; is necessary because unlike a native C++ type's destructor, which may only be called once, an managed type's Disposeimplementation may be called repeatedly, and doing so must have defined behavior.)
Or, better yet, in addition to exposing a GetInstance function, also expose a DestroyInstance function and call that instead of using delete so that consuming code does not need to depend on the implementation details of GetInstance (i.e., that it allocates its instance using operator new).


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|抱朴守拙BBS

GMT+8, 2025-5-26 04:39 , Processed in 0.181598 second(s), 18 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表