C++-C#接口中的智能指针

Smart pointers in C++ - C# interface

本文关键字:智能 指针 接口 C++-C#      更新时间:2023-10-16

我正在构建要从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;
};