[英]AccesViolationException in C++/CLI Wrapper for native C
[英]How to make CLI / C++ Wrapper of C++ native?
這是我的本機文件...
1.)test.h
#if !defined (TEST)
#define TEST
namespace ABB
{
namespace CRLDownload_Native
{
class A
{
public:
int x;
int init();
};
class B : public A
{
public:
int abc();
};
}
}
#endif
2.)test.cpp
#include"test.h"
using namespace ABB::CRLDownload_Native;
int A::init()
{
x = 15;
return 20;
}
int B::abc()
{
return x;
}
這個文件是我的本機代碼。 我想將其包裝在CLI / C ++項目中。
下面的文件是CLI / C ++代碼。
3.)test_cli.h
#if!defined (TEST_CLR)
#define TEST_CLR
#include"test.h"
namespace ABB
{
namespace CRLDownload_CLR
{
// ref class B;
namespace native = ABB::CRLDownload_Native;
public ref class A
{
public:
A();
~A();
!A();
int init();
native::A * obj1;
};
public ref class B : public A
{
public:
B();
~B();
!B();
int abc();
native ::B * obj;
};
}
}
#endif
4.)test_cli.cpp
#include"test_clr.h"
using namespace ABB::CRLDownload_CLR;
A::A()
{
obj1 = new native :: A;
}
A :: !A()
{
}
A :: ~A()
{
}
int A::init()
{
return (obj1->init());
}
B::B()
{
obj = new native ::B;
}
B ::~B()
{
}
B ::!B()
{
}
int B::abc()
{
return (obj->abc());
}
我要使用C#訪問此CLI / C ++庫。 所以如果我創建
int ret=-1;
B Obj;
ret=obj.init();
ret=obj.abc();
最后ret應該是15,但我沒有得到。 誰能幫我?
這不會返回15,因為您有兩個單獨的本機A和B對象,並且分別在一個對象上調用init()和在另一個對象上調用abc()。 建議:使用調試器單步執行代碼,您會立即注意到。
最簡單的解決方案是不重復包裝程序中的類層次結構,而僅提供B,例如:
public ref class B
{
public:
B() : obj( new native::B() ){}
~B() { this->!B(); }
!B() { delete obj; obj = nullptr; }
int init() { return obj->init(); }
int abc() { return obj->abc(); }
private:
native::B* obj;
};
並且不要忘記實施銷毀操作,否則您將發生內存泄漏。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.