how to write c wrapper around c++ code to expose class methods

。_饼干妹妹 提交于 2019-12-12 02:42:40

问题


I have number of cpp files in unmanaged c++ , I want to access class methods of these files from vb .net using P\Invoke, For that i have write C wrapper for exposing class methods.Can anybody help me ,how to write a c wrapper around C++ code. I am copying some code of my files ,please help me writting c wrapper for these function.

#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;
}

回答1:


In 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 */

In 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:


It'll be like:

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());
    }
}

More info at Oracle pages



来源:https://stackoverflow.com/questions/7929905/how-to-write-c-wrapper-around-c-code-to-expose-class-methods

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!