C++-C#接口中的智能指针
Smart pointers in C++ - C# interface
我正在构建要从C#程序调用的C++接口(使用Dlliport.dll导出)。我需要在工作中使用一些指针。因此,我创建了一个(create_engine)方法和(destroy_enginee)方法。有没有一种方法可以使用智能指针,这样我就不再需要destroy方法了。
代码:
extern "C" _declspec (dllexport) Engine* create_engine(){
return new Engine();
}
extern "C" _declspec (dllexport) void destroy_engine(Engine* engine){
if (engine != NULL){
delete engine;
}
engine = NULL;
}
附言:智能指针将从C#中使用,因此它应该继续计算有多少引用,即使是从C#部分。。。感谢
不,你不能这么做。半手动半自动的内存管理不是一种选择。
你能做的最接近的想法是包装C++类供C#使用,并用shared_ptr管理那里的内存。示例在MSDN上(下面的代码也取自MSDN):由C#使用的包装本机类
// wrap_native_class_for_mgd_consumption.cpp
// compile with: /clr /LD
#include <windows.h>
#include <vcclr.h>
#using <System.dll>
using namespace System;
class UnmanagedClass {
public:
LPCWSTR GetPropertyA() { return 0; }
void MethodB( LPCWSTR ) {}
};
public ref class ManagedClass {
public:
// Allocate the native object on the C++ Heap via a constructor
ManagedClass() : m_Impl( new UnmanagedClass ) {}
// Deallocate the native object on a destructor
~ManagedClass() {
delete m_Impl;
}
protected:
// Deallocate the native object on the finalizer just in case no destructor is called
!ManagedClass() {
delete m_Impl;
}
public:
property String ^ get_PropertyA {
String ^ get() {
return gcnew String( m_Impl->GetPropertyA());
}
}
void MethodB( String ^ theString ) {
pin_ptr<const WCHAR> str = PtrToStringChars(theString);
m_Impl->MethodB(str);
}
private:
UnmanagedClass * m_Impl;
};
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 优先顺序:智能指针和类析构函数
- 对于C++中使用智能指针的指针算术限制,有没有一种变通方法
- 智能指针作为无序映射键,并通过引用进行比较
- 智能指针概念所有权和寿命
- 正在理解智能指针,但出现错误:未分配正在释放的指针
- 尝试使用智能指针时引发异常
- 我可以制作指向智能指针的智能指针吗?
- 通过智能指针和转换对基本模板参数进行模板推导
- OpenCV 我应该使用智能指针来防止内存泄漏吗?
- 从堆栈分配的原始指针构造智能指针
- 初始化指向类实例的智能指针并访问其方法
- 如何使用 std::make_shared 创建基类类型的智能指针?
- 给定一个指向堆分配内存的指针,智能指针实现如何为其找到合适的释放函数?
- 编译器不会使用 -std=c++11 编译智能指针
- 具有智能指针的多态性
- C++:矢量分配器行为、内存分配和智能指针
- 在什么情况下,需要共享智能指针而无法使用唯一指针?
- 指向函数签名中的常量智能指针
- 使用智能指针附加的继承对象的深层复制