2011-10-14 1 views

답변

4

나는 대부분 SWiG이 그렇게 할 것이라고 생각합니다.

0

이 작업을 자동으로 수행 할 수있는 도구에 대해 알지 못하는데, API에서 공용 함수에 대한 인수로 클래스를 사용하면 매우 까다로워 질 수 있습니다.

API가 단순하고 대부분 기본 유형을 사용하는 경우 너무 많은 작업을하지 않아도이 작업을 직접 수행 할 수 있습니다. 다음은 C++ 클래스 용 C 랩퍼의 빠른 예제입니다.

typedef void* TestHandle; 
TestHandle newTest(); 
int deleteTest(TestHandle h); 
int Test_do_something(TestHandle h, char* arg); 

그리고 C 기능,하자가있는 C++ 파일을하게 될 C 구현 :

class Test { 
public: 
    Test(); 
    int do_something(char* arg); 
    bool is_valid(); // optional, but recommended (see below) 
}; 

이 당신의 C 헤더 test_c.h입니다 :의이 test.h를 호출하자의이 바꿈하는 C++ 클래스입니다 가정 해 봅시다 test_c.cpp 말 :

extern "C" TestHandle newTest() 
{ 
    return (void*)new Test(); 
} 

extern "C" int deleteTest(TestHandle h) 
{ 
    Test* this = static_cast<Test*>(h); 
    if (!this->is_valid()) 
     return -1; // here we define -1 as "invalid handle" error 
    delete this; 
    return 0; // here we define 0 as the "ok" error code 
} 

extern "C" int Test_do_something(TestHandle h, char* arg) 
{ 
    Test* this = static_cast<Test*>(h); 
    if (!this->is_valid()) 
     return -1; // here we define -1 as "invalid handle" error 
    return this->do_something(arg); 
} 

is_valid() 방법은 당신이 나쁜 핸들을 부여되지 않았 음을 보장 할 수있다. 예를 들어 magic number을 모든 인스턴스에 저장할 수 있으며 is_valid()은 마법 번호가 있음을 보장합니다.