【问题标题】:how to write c wrapper around c++ code to expose class methods如何围绕 C++ 代码编写 C 包装器以公开类方法
【发布时间】:2011-10-28 13:27:46
【问题描述】:

我在非托管 c++ 中有许多 cpp 文件,我想使用 P\Invoke 从 vb .net 访问这些文件的类方法,为此我编写了 C 包装器来公开类方法。谁能帮助我,如何围绕 C++ 代码编写一个 c 包装器。我正在复制我的文件的一些代码,请帮我为这些函数编写 c 包装器。

#include "StdAfx.h"
#include "Verify.h"

Verify::Verify(void)
    :_verified(false)
{
}

Verify::~Verify(void)
{
}

void Verify::SetVerified(bool value)
{
    _verified = value;
}

bool Verify::GetVerified(void) const
{
        _verified;
}

void Verify::SetFailurePoint(std::basic_string<TCHAR> const & value)
{
    _failurePoint = value;
}

std::basic_string<TCHAR> const & Verify::GetFailurePoint(void) const
{
    return _failurePoint;
}

【问题讨论】:

    标签: wrapper


    【解决方案1】:

    在 wrapper.h 中:

        typedef void * VERIFY_HANDLE;
        extern VERIFY_HANDLE Verify_Create();
        extern void VERIFY_SetVerified(VERIFY_HANDLE, bool);
        extern bool VERIFY_GetVerified(VERIFY_HANDLE);
        /* etc, etc */
    

    在 wrapper.c 中:

        #include "wrapper.h"
        #include "Verify.h"
        VERIFY_HANDLE Verify_Create() { return (VERIFY_HANDLE) new Verify(); }
        void SetVerified(VERIFY_HANDLE h, bool b) { ((Verify *)h)->SetVerified(b); }
        bool GetVerified(VERIFY_HANDLE h) { return ((Verify *)h)->GetVerified();  }
    

    【讨论】:

      【解决方案2】:

      会是这样的:

      extern "C" {
          typedef void *VERIFY;
      
          VERIFY create_verify() {
              return (VERIFY)new Verify();
          }
          void verify_set(VERIFY verify, int value) {
              ((Verify*)verify)->SetVerified((bool)value);
          }
          int verify_get(VERIFY verify) {
              return ((int)((Verify*)verify)->GetVerified());
          }
      }
      

      更多信息Oracle pages

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-03-07
        • 1970-01-01
        • 1970-01-01
        • 2011-06-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多