Skip to content

Instantly share code, notes, and snippets.

@yuu
Last active August 23, 2019 06:09
Show Gist options
  • Save yuu/af7716ca147f0fae89fdc93202c9524c to your computer and use it in GitHub Desktop.
Save yuu/af7716ca147f0fae89fdc93202c9524c to your computer and use it in GitHub Desktop.
[c++] Wrap c struct and c++ class

C++ Wrap example

1. make shared library

g++ -c -Wall -Werror -shared -fpic lib.cpp -o libhoge.so

2. make exec

gcc main.c -L$(pwd) -lhoge -lstdc++
#include "lib.h"
#include "lib_c.h"
#include <iostream>
void A::print() {
std::cout << "Hello lib World" << std::endl;
}
A *create_a() {
return new A();
}
void print(A *a) {
a->print();
}
#pragma once
class A {
public:
enum ER {
OK = 0,
NG,
};
void print();
};
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
struct A;
struct A *create_a();
void print(struct A *a);
#ifdef __cplusplus
};
#endif
#include "lib_c.h"
int main(int argc, char **argv) {
struct A *hoge = create_a();
print(hoge);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment