I am learning how to generate an array of random numbers in C++. I am using a std::vector and std::generate (I'm trying to use modern idiomatic C++ - not sure how well I'm doing).
What I would like to do is to expose this function to plain old C code. How can make this function available from C?
Code below. Thanks!
void RandomArray(std::vector<double> &data)
{
std::random_device rd{};
auto mtgen = std::mt19937{ rd() };
auto ud = std::uniform_int_distribution<>{ 1, 6 };
auto gen = [&ud, &mtgen](){ return ud(mtgen); };
std::generate(data.begin(), data.end(), gen);
}
You can use the extern "C" statement to make the function linkable to C code.
But working from your C++ version to the C version is harder I think, it would go something like this:
void RandomArray(std::vector<double> &data)
{
std::random_device rd{};
auto mtgen = std::mt19937{ rd() };
auto ud = std::uniform_int_distribution<>{ 1, 6 };
auto gen = [&ud, &mtgen](){ return ud(mtgen); };
std::generate(data.begin(), data.end(), gen);
}
extern "C" void RandomArray(double* data, size_t size)
{
std::vector<double> v(size);
RandomArray(v);
std::copy(std::begin(v), std::end(v), data); // need to copy out
}
Personally I would go the other way and make the C version the main algorithm and get the C++ version to call that:
extern "C" void RandomArray(double* data, size_t size)
{
std::random_device rd{};
auto mtgen = std::mt19937{ rd() };
auto ud = std::uniform_int_distribution<>{ 1, 6 };
auto gen = [&ud, &mtgen](){ return ud(mtgen); };
std::generate(data, data + size, gen);
}
void RandomArray(std::vector<double>& data)
{
RandomArray(data.data(), data.size());
}
Also it would be a lot faster not to initialize the random generator each time you call the function. One way to do that is making the random generator static. If you need thread safety you could also make it thread_local:
extern "C" void RandomArray(double* data, size_t size)
{
thread_local static auto mtgen = std::mt19937{std::random_device{}()};
auto ud = std::uniform_int_distribution<>{ 1, 6 };
std::generate(data, data + size, [&ud](){ return ud(mtgen); });
}
While C++ has standard support to call C functions, the reverse is not true. The only way to call a C++ function from C code is to make it C-compatible and use the C++ facilities to call it as a C function (only the function internal body code is C++ code), and compile it with a C++ compiler, to produce a C++ object code that has a C entry point
mod.h
#ifdef __cplusplus
extern "C" {
#endif
void my_function(const char *sample_parameter1, const int sample_parameter2);
#ifdef __cplusplus
}
#endif
mod.cc
#include <iostream>
#include "mod.h"
void my_function(const char *sample_parameter1, const int sample_parameter2)
{
std::cout << sample_parameter1
<< ", "
<< sample_parameter2
<< std::endl;
}
And then
main.c
#include <stdlib.h>
#include "mod.h"
int main()
{
my_function("Sample literal 1", 37);
exit(EXIT_SUCCESS);
}
To compile this, you need the following sequence:
$ c++ -o mod.o -c mod.cc
$ cc -o main.o -c main.c
$ c++ main.o mod.cc
$ a.out
(You need to invoque c++ to make the link phase, as it needs to include the standard c++ modules required at link time)
As far as you have included a c++ module, the whole project must be considered a c++ project and not C, because you'll need the C++ runtime modules to initialize properly all the global c++ objects you declare in your c++ modules and to include the c++ libraries you may use. You'll only compile with the cc C compiler only the modules that are pure C (and you have to use the C++ rules to distinguish them as C code)
The c++ compiler uses a different naming procedure for identifiers and all the C identifiers must be marked extern "C" (that's the reason of the mod.h file) If you don't follow that you'll lead to a unknown function 'my_function' linker message because C++ names include information about the parameter list types used in them, to allow for overloaded function names.
Related
I am a beginner in C and slightly more advanced in C++. This is my first time using make.
I have a large C++ library (written by a third-party that I need to integrate into a C pipeline) and I am hoping to call this library from C. In order to call the C++ library from C, I have 3 files: a .cpp file implementing the calls to the C++ library with C-compatible data types, a .h C-compatible header file linking the C++ implementation functions to C, and a .c file with a main() function that calls the C++ function with C-appropriate data types.
The header file (random_forest.h):
#ifndef RANDOMFOREST_H_
#define RANDOMFOREST_H_
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
// opaque forward declared struct
struct random_forest_model;
// pointer to struct used by C code
typedef struct random_forest_model* random_forest_model_t;
random_forest_model_t random_forest_new(const char* model_file_path);
void random_forest_free(random_forest_model_t random_forest_model);
uint8_t *classify(
random_forest_model_t random_forest_model,
const double* independentVariableData,
const double* dependentVariableData,
const size_t numberRows,
const size_t numberColumns,
const char** independentVariableNames
);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* RANDOMFOREST_H_ */
In my random_forest.cpp file:
#include <memory.h>
#include "/src/random_forest.h"
#include "/src/rf/src/Forest.h"
#include "/src/rf/src/globals.h"
#include "/src/rf/src/ForestClassificationPrediction.h"
#include "/src/rf/src/utility.h"
using namespace rf; /* comes from Forest.h file */
struct random_forest_model {
std::unique_ptr<rf::Forest> forest;
std::string model_file_path;
}
namespace {
std::unique_ptr<rf::Forest> random_forest_acquire(const char* model_file_path) {
try {
std::unique_ptr<rf::Forest> forest = make_unique<ForestClassificationPrediction>();
forest->InitPredictionModelCpp(model_file_path);
return forest;
} catch(...) {
return nullptr;
}
}
} /* anonymous namespace */
random_forest_model_t random_forest_new(const char* model_file_path) {
try {
auto forest = random_forest_acquire(model_file_path);
return new random_forest_model{std::move(forest), model_file_path};
} catch (...) {
return nullptr;
}
}
void random_forest_free(random_forest_model_t random_forest_model) {
delete random_forest_model;
}
uint8_t* classify(
ranger_random_forest_model_t ranger_random_forest_model,
const double* independentVariableData,
const double* dependentVariableData,
const size_t numberRows,
const size_t numberColumns,
const char** independentVariableNames
) {
try {
/* bunch of stuff here to convert data and run classification */
} catch(...) {
return nullptr;
}
}
Then in my random_forest_implement.c file:
#include "/src/random_forest.h"
int main() {
const char model_file_path[] = "path/to/model";
random_forest_model_t random_forest = random_forest_new(model_file_path);
/*
some code here to ingest a data file - outputting the data for random_forest_classify
yielding: X, y, numberRows, numberColumns, varNames
*/
uint8_t *classes = classify(
random_forest, X, y, numberRows, numberColumns, varNames
);
random_forest_free(random_forest);
free(X);
free(y);
free(varNames);
free(classes);
return EXIT_SUCCESS;
}
This is a very long-winded way to ask how to compile this program into a single executable. I've tried to compile with the following make file:
CC ?= gcc
CP ?= g++
random_forest_implement: random_forest_implement.o random_forest.o
$(CP) -o random_forest_implement random_forest_implement.o random_forest.o
random_forest.o: random_forest.cpp random_forest.h
$(CP) -c random_forest.cpp
random_forest_implement.o: random_forest_implement.c random_forest.h
$(CC) -c random_forest_implement.c random_forest.h
clean:
$(RM) *.o random_forest
When I try to make this (make -f random_forest_make.mk), I get three lines that appear (?) successful, and I receive a lot of errors about undefined reference, e.g.:
cc -c random_forest.c random_forest.h
g++ -c random_forest.cpp
g++ -o random_forest_implement random_forest_implement.o random_forest.o
/usr/bin/ld: random_forest.o: in function `(anonymous namespace)::random_forest_acquire(char const*)':
random_forest.cpp:(.text+0x44f): undefined reference to `rf::Forest::InitPredictionModelCpp(<bunch of args necessary to method>)
I'm not entirely sure where to go from here, but I suspect I'm not compiling everything correctly. As you can see, I have several files on which my random_forest.cpp file depends. Do I need to compile each of these? And their dependencies? Is there a best/efficient method for doing this, or do I need to write a make file that generates an object file for every .cpp file in the /src/rf/src/ directory?
You cannot build a C executable including C++ sources. You can only create C++ executables if you include any C++ code. C++ supports C source modules to be linked against for compatibility reasons but C compilers were not designed to link C++ modules (there’s no backwards compatibility between C and C++, C was created before)
For this reason, you can only use c++ compiler to link C++ mixed with C sources (even if main is defined in a C source file) because this action will make C++ compiler to call the linker in C++ mode and link both C/C++ modules and call the C++ standard library modules and run time. Despite of the similarities between both languages, the memory layout of a C++ executable is more complex than the layout of a simple C-only program
I'm trying to use opencv C++ library with another lib in C. So I've defined a structure in an .hpp file which I've added to the .h of the C library
typedef struct {
cv::FileStorage fs;
cv::Mat mat;
} myCPPStruct;
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
myCPPStruct * mycppstruct;
} myCStruct;
void initialize_myCPPStruct(myCPPStruct * mycppstruct);
#ifdef __cplusplus
}
#endif
In the .c files the initializer for myCStruct calls initialize_myCPPStruct which is defined in a .cpp file somewhat as:
void initialize_myCPPStruct(myCPPStruct * mycppstruct){
mycppstruct = {};
mycppstruct->fs = cv::FileStorage( "file.txt", cv::FileStorage::READ );
mycppstruct->mat = cv::Mat(3,3,CV_8UC3);
}
But once it tries to allocate a value to mycppstruct->fs, it gets a segmentation fault. I assume this is because there is no memory allocation in C, but I've tried
std::memset(stitcher->fs,0,sizeof(cv::FileStorage));
which also doesn't work as it can't parse cv:FileStorage as void *.
Will I have to use the deprecated C OpenCV library to make this work?
EDIT - More details about the compilation.
For the C lib, I recompile (without linking ie with the -c option)all the .c files where I've added C++ functions or structures using g++ while making sure I add the __cplusplus guards in the .h files. All the .c files without C++ code already have .o files compiled with gcc. I then compile the whole program with g++ while making sure to include the relevant library files. There are no compiler errors.
It seems the structure itself has not been created.
You might try this (or something similar):
myCPPStruct* initialize_myCPPStruct()
{
myCPPStruct* result;
result = new myCPPStruct();
result->fs = cv::FileStorage( "file.txt", cv::FileStorage::READ );
result->mat = cv::Mat(3,3,CV_8UC3);
return (result);
}
You need to allocate the memory for your structure:
myCPPStruct = malloc(sizeof(myCPPStruct));
Use the above line instead of:
mycppstruct = {};
Also,since your function is passing in the pointer and allocating the memory internally you need to pass a pointer to the pointer or the allocation will not be passed back:
void initialize_myCPPStruct(myCPPStruct** mycppstruct){
if ( mycppstruct == NULL ) {
//Abort as no address of the pointer to allocate passed
return;
}
*myCPPStruct = malloc(sizeof(myCPPStruct));
(*mycppstruct)->fs = cv::FileStorage( "file.txt", cv::FileStorage::READ );
(*mycppstruct)->mat = cv::Mat(3,3,CV_8UC3);
}
Or you could just change the above to:
myCPPStruct* initialize_myCPPStruct(void) {
myCPPStruct* ptr = malloc(sizeof(myCPPStruct));
ptr->fs = cv::FileStorage( "file.txt", cv::FileStorage::READ );
ptr->mat = cv::Mat(3,3,CV_8UC3);
return ptr;
}
First, let me point out the sentence which confuse me.
there is no memory allocation in C
Yes, there is. Have a look to malloc function.
char *my_allocated_string = malloc(sizeof(char) * 42);
Here you are, you've allocated an array of character of size 42.
Now, have a look to : mycppstruct = {};
That's not how you allocate a structure in C. You have to call... malloc() !
my_struct *s = malloc(sizeof(my_struct));
s->fs = 42;
Ok. Done. Feels better.
Well, first of all, you have to create a wrapper around your C++ code. Why ? Because C++ allows multiple definition of a given function (also call symbol) :
int my_func(int);
int my_func(char);
This is valid in C++. But, think about it, how is the compiler able to let two functions with the same name exist ? Well it's not. It uses a technique named mangling when evaluating the functions to create 2 different names. Mangling is use on everything function and method. Event on single functions.
C is not able (and willing) to create several functions with the same name. Otherwise, you will experience a kind of function-already-implemented error. When you declare :
int my_func(int);
the C compiler will create the symbol : my_func. No mangling.
To make both language interact, you need to reference to a symbol understandable by the C compiler. If you call my_func from a C source file, the C compiler will look for my_func symbol. Bu since C++ will modify its my_func symbol into something like _ZN9myfuncE, the linkage will fail. That's why you have to says to the C++ compiler to not use mangling on the function you expose to C. That's why you need extern "C" { }.
Feeww, so far so good...
Now you have to embed you C API into an extern "C" block :
In my_c_api.h :
void my_func(int);
void my_func(char);
In my_c_api.cpp :
#include "my_c_api.h"
extern "C" void my_func_i(int i) { my_func(i); }
extern "C" void my_func_c(char c) { my_func(c); }
You compile it to create your C++ library.
In your C compilation pipeline, you link against your new C++ library and header files. Then :
#include "<path_to_my_c_api.h>"
void c(int i,char s)
{
my_func_i(i);
my_func_c(c);
}
You cannot compile C++ code with C compiler. You have to compile te C++ code independently.
More on ISO CPP.
This has been driving me nuts for a long time now. I have followed every tutorial I could find on the internet (here are couple examples[ [1], [2] of the maybe half dozen good ones found via Google search), and still no clear explanation. Although it seems it must be something fairly simple as that lack of a documented explanation implies that it's something most people would take for granted.
How do I load a custom module into Lua?
On the advice of questions like this one, I have written a module that builds a shared library with the expectation that I would be able to load it through a require call. However, when I do that I get undefined symbol errors, despite those exact symbols appearing in the list from the command nm -g mylib.so.
Those two tutorials I linked before aim to create executables that look wrappers of the *.lua file. That is, the built *.exe file should be called to run the Lua program with the custom module.
I understand that these types questions are asked here fairly frequently (as noted in this answer), but I am still at a loss. I tried some of the binding packages (Luabind and OOLua), but those didn't work out great (e.g. my earlier question--which I did ultimately figure out, sort of).
I have implemented a class in C++
I have wrapped the constructors, destructors, and functions with thunks
I have built it errorless-ly as a shared library
Yet no matter what I get undefined symbol: ... errors when I try to load it as mod = require('mylib.so'). How do I do this?
Working Example of a Library of Functions
For the record, just registering a basic function works fine. The below code, when built as libluatest.so, can be run in Lua using the commands:
> require('libluatest')
> greet()
hello world!
libluatest.cpp
extern "C"
{
#include <lualib.h>
#include <lauxlib.h>
#include <lua.h>
}
#include <iostream>
static int greet(lua_State *L)
{
std::cout << "hello world!" << std::endl;
return 0;
}
static const luaL_reg funcs[] =
{
{ "greet", greet},
{ NULL, NULL }
};
extern "C" int luaopen_libluatest(lua_State* L)
{
luaL_register(L, "libluatest", funcs);
return 0;
}
Failing Example of a Class
This is what I am stuck on currently. It doesn't seem to want to work.
myObj.h
#include <string>
class MyObj
{
private:
std::string name_;
public:
MyObj();
~MyObj();
void rename(std::string name);
};
myObj.cpp
extern "C"
{
#include <lualib.h>
#include <lauxlib.h>
#include <lua.h>
}
#include <iostream>
#include "myObj.h"
void MyObj::rename(std::string name)
{
name_ = name;
std::cout << "New name: " << name_ << std::endl;
}
extern "C"
{
// Lua "constructor"
static int lmyobj_new(lua_State* L)
{
MyObj ** udata = (MyObj **)lua_newuserdata(L, sizeof(MyObj));
*udata = new MyObj();
luaL_getmetatable(L, "MyObj");
lua_setmetatable(L, -1);
return 1;
}
// Function to check the type of an argument
MyObj * lcheck_myobj(lua_State* L, int n)
{
return *(MyObj**)luaL_checkudata(L, n, "MyObj");
}
// Lua "destructor": Free instance for garbage collection
static int lmyobj_delete(lua_State* L)
{
MyObj * obj = lcheck_myobj(L, 1);
delete obj;
return 0;
}
static int lrename(lua_State* L)
{
MyObj * obj = lcheck_myobj(L, 1);
std::string new_name = luaL_checkstring(L, 2);
obj->rename(new_name);
return 0;
}
int luaopen_libmyObj(lua_State* L)
{
luaL_Reg funcs[] =
{
{ "new", lmyobj_new }, // Constructor
{ "__gc", lmyobj_delete }, // Destructor
{ "rename", lrename }, // Setter function
{ NULL, NULL } // Terminating flag
};
luaL_register(L, "MyObj", funcs);
return 0;
}
}
Compiled into libmyObj.so using a simple CMake build with C++11 standard flags on.
Error
> require('libmyObj')
error loading module 'libmyObj' from file './libmyObj.so':
./libmyObj.so: undefined symbol: _ZN5MyObjC1Ev stack traceback: [C]:
? [C]: in function 'require' stdin:1: in main chunk [C]: ?
I am dealing with Lua 5.1 on Ubuntu 14.04.
I am wondering if it has something to do with the mix of C and C++...
It seems that you do not implement:
MyObj() ; ~MyObj();
and be careful with luaopen_* function, since module name is myObj, function name should be luaopen_libmyObj.
I have a command line (+HTTP interface) audio application in C, which currently is being compiled with gcc on Mac OSX, but which I would like to keep this application linux compatible.
However, I would like to use the freeverb3 library. This is in C++. I would prefer not to convert all my code to C++. I don't (as far as I can see) need to call any C code from C++, nor will I need to use C++ objects in my C code. Simple method calls passing arrays of doubles plus a few ints as arguments will be all that I need in terms of interaction from my main application an the C++ code.
From some quick googling, it seems that I can write a C++ interface module, which can then expose some c compatible functions that I can call to make use of freeverb3. I"ve written a micro example to see how this might work. For this example, I have a dummy c++ file called test.cpp:
#include <iostream>
using namespace std;
class test_class
{
int a;
public:
int get_a();
void set_a( int v );
};
int test_class::get_a()
{
return a;
}
void test_class::set_a( int v )
{
a = v;
}
static test_class *c;
extern "C"
{
void init();
void set( int v );
int get();
}
void init()
{
c = new test_class();
}
void set( int v )
{
c->set_a( v );
}
int get()
{
return c->get_a();
}
I have a dummy c file that calls the functions:
#include <stdio.h>
/* Forward declaratoins for extern "C" functions in C++ code */
void init();
int get();
void set( int v );
/* C language code that references functions in C++ code */
int main()
{
init();
set( 55 );
printf( "value: %d\n", get() );
set( get() + 12 );
printf( "value: %d\n", get() );
return 0;
}
And, I have a makefile that creates an executable.
test: test.o user.o
g++ -o test user.o test.o
test.o: test.cpp
g++ -c test.cpp
user.o: user.c
gcc -c user.c
Is this a good way of using C++ code from C? Is there a better/more sophisticated/more traditional way of achieving this aim?
You might want to think about it the other way.
Write your higher level application in C++, invoke the C++ library where you want without complications and call all your current C modules from the C++ level.
IMHO, this is easier to achieve than doing the same with C as high level.
If you intend to use more than one C++ object from C you need to pass an extra instance pointer (this) to the C wrapper functions:
struct A {
A();
~A();
void set(int);
};
The C wrapper:
extern "C"
{
struct A* a_create(void);
void a_destroy(struct A*);
void a_set(struct A*, int);
}
You may also like to catch all C++ exceptions in the C wrapper functions and convert them to error codes.
Pass a pointer to your object instead of using a static variable.
C++ class:
class Foo
{
public:
void doStuff();
};
Common include file:
#ifdef __cplusplus
extern "C"
{
#endif
void Foo_doStuff(void* handle);
void* Foo_create();
void Foo_destroy(void* handle);
#ifdef __cplusplus
}
#endif
Wrapper functions
void Foo_doStuff(void* handle)
{((Foo*)handle)->doStuff();}
void* Foo_create()
{return new(nothrow)Foo;}
void Foo_destroy(void* handle)
{delete (Foo*)handle;}
Not sure whether this goes from C to C++ but it is well worth looking into Swig
Make an extern "C" wrapper in C++, e.g.
// myWrapper.h
#ifdef __cplusplus
extern "C"
{
#endif
void func1(void);
int func2(void);
void func3(char const *str_ptr, size_t len);
#ifdef __cplusplus
}
#endif
// myWrapper.cpp
#include "myWrapper.h"
#include "your_cpp_library.h"
void func3(char const *str_ptr, size_t len)
{
std::string s(str_ptr, str_ptr + len);
call_cpp_function(s);
}
// etc.
In your C code you #include "myWrapper.h" and call those functions. Make sure that:
The code in myWrapper.h stays in the common subset of C and C++
You do not do any cross-boundary resource allocation
The latter might work but it's best to avoid it to be safe. The latter point means that if memory is to be allocated, it must be allocated and freed by the same side; e.g. you can't have the C++ side call malloc and give a pointer to the C side, and then have the C side call free. You have to pass the pointer back to whoever allocated it and let them free it.
Important: as Alf says in a comment, you must have main() in C++ and use the C++ linker , when doing C - C++ inter-linking. This is not a big hurdle though; you can rename your C code's main() function to main2(), and have the C++ code do extern "C" int main2(); and call it.
In the new Go language, how do I call C++ code? In other words, how can I wrap my C++ classes and use them in Go?
Update: I've succeeded in linking a small test C++ class with Go
If you wrap you C++ code with a C interface you should be able to call your library with cgo (see the example of gmp in $GOROOT/misc/cgo/gmp).
I'm not sure if the idea of a class in C++ is really expressible in Go, as it doesn't have inheritance.
Here's an example:
I have a C++ class defined as:
// foo.hpp
class cxxFoo {
public:
int a;
cxxFoo(int _a):a(_a){};
~cxxFoo(){};
void Bar();
};
// foo.cpp
#include <iostream>
#include "foo.hpp"
void
cxxFoo::Bar(void){
std::cout<<this->a<<std::endl;
}
which I want to use in Go. I'll use the C interface
// foo.h
#ifdef __cplusplus
extern "C" {
#endif
typedef void* Foo;
Foo FooInit(void);
void FooFree(Foo);
void FooBar(Foo);
#ifdef __cplusplus
}
#endif
(I use a void* instead of a C struct so the compiler knows the size of Foo)
The implementation is:
//cfoo.cpp
#include "foo.hpp"
#include "foo.h"
Foo FooInit()
{
cxxFoo * ret = new cxxFoo(1);
return (void*)ret;
}
void FooFree(Foo f)
{
cxxFoo * foo = (cxxFoo*)f;
delete foo;
}
void FooBar(Foo f)
{
cxxFoo * foo = (cxxFoo*)f;
foo->Bar();
}
with all that done, the Go file is:
// foo.go
package foo
// #include "foo.h"
import "C"
import "unsafe"
type GoFoo struct {
foo C.Foo;
}
func New()(GoFoo){
var ret GoFoo;
ret.foo = C.FooInit();
return ret;
}
func (f GoFoo)Free(){
C.FooFree(unsafe.Pointer(f.foo));
}
func (f GoFoo)Bar(){
C.FooBar(unsafe.Pointer(f.foo));
}
The makefile I used to compile this was:
// makefile
TARG=foo
CGOFILES=foo.go
include $(GOROOT)/src/Make.$(GOARCH)
include $(GOROOT)/src/Make.pkg
foo.o:foo.cpp
g++ $(_CGO_CFLAGS_$(GOARCH)) -fPIC -O2 -o $# -c $(CGO_CFLAGS) $<
cfoo.o:cfoo.cpp
g++ $(_CGO_CFLAGS_$(GOARCH)) -fPIC -O2 -o $# -c $(CGO_CFLAGS) $<
CGO_LDFLAGS+=-lstdc++
$(elem)_foo.so: foo.cgo4.o foo.o cfoo.o
gcc $(_CGO_CFLAGS_$(GOARCH)) $(_CGO_LDFLAGS_$(GOOS)) -o $# $^ $(CGO_LDFLAGS)
Try testing it with:
// foo_test.go
package foo
import "testing"
func TestFoo(t *testing.T){
foo := New();
foo.Bar();
foo.Free();
}
You'll need to install the shared library with make install, then run make test. Expected output is:
gotest
rm -f _test/foo.a _gotest_.6
6g -o _gotest_.6 foo.cgo1.go foo.cgo2.go foo_test.go
rm -f _test/foo.a
gopack grc _test/foo.a _gotest_.6 foo.cgo3.6
1
PASS
Seems that currently SWIG is best solution for this:
https://www.swig.org/Doc4.0/Go.html
It supports inheritance and even allows to subclass C++ class with Go struct so when overridden methods are called in C++ code, Go code is fired.
Section about C++ in Go FAQ is updated and now mentions SWIG and no longer says "because Go is garbage-collected it will be unwise to do so, at least naively".
As of go1.2+, cgo automatically incorporates and compiles C++ code:
http://golang.org/doc/go1.2#cgo_and_cpp
You can't quite yet from what I read in the FAQ:
Do Go programs link with C/C++ programs?
There are two Go compiler implementations, gc (the 6g program and friends) and gccgo. Gc uses a different calling convention and linker and can therefore only be linked with C programs using the same convention. There is such a C compiler but no C++ compiler. Gccgo is a GCC front-end that can, with care, be linked with GCC-compiled C or C++ programs.
The cgo program provides the mechanism for a “foreign function interface” to allow safe calling of C libraries from Go code. SWIG extends this capability to C++ libraries.
I've created the following example based on Scott Wales' answer. I've tested it in macOS High Sierra 10.13.3 running go version go1.10 darwin/amd64.
(1) Code for library.hpp, the C++ API we aim to call.
#pragma once
class Foo {
public:
Foo(int value);
~Foo();
int value() const;
private:
int m_value;
};
(2) Code for library.cpp, the C++ implementation.
#include "library.hpp"
#include <iostream>
Foo::Foo(int value) : m_value(value) {
std::cout << "[c++] Foo::Foo(" << m_value << ")" << std::endl;
}
Foo::~Foo() { std::cout << "[c++] Foo::~Foo(" << m_value << ")" << std::endl; }
int Foo::value() const {
std::cout << "[c++] Foo::value() is " << m_value << std::endl;
return m_value;
}
(3) Code for library-bridge.h the bridge needed to expose a C API implemented in C++ so that go can use it.
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
void* LIB_NewFoo(int value);
void LIB_DestroyFoo(void* foo);
int LIB_FooValue(void* foo);
#ifdef __cplusplus
} // extern "C"
#endif
(4) Code for library-bridge.cpp, the implementation of the bridge.
#include <iostream>
#include "library-bridge.h"
#include "library.hpp"
void* LIB_NewFoo(int value) {
std::cout << "[c++ bridge] LIB_NewFoo(" << value << ")" << std::endl;
auto foo = new Foo(value);
std::cout << "[c++ bridge] LIB_NewFoo(" << value << ") will return pointer "
<< foo << std::endl;
return foo;
}
// Utility function local to the bridge's implementation
Foo* AsFoo(void* foo) { return reinterpret_cast<Foo*>(foo); }
void LIB_DestroyFoo(void* foo) {
std::cout << "[c++ bridge] LIB_DestroyFoo(" << foo << ")" << std::endl;
AsFoo(foo)->~Foo();
}
int LIB_FooValue(void* foo) {
std::cout << "[c++ bridge] LIB_FooValue(" << foo << ")" << std::endl;
return AsFoo(foo)->value();
}
(5) Finally, library.go, the go program calling the C++ API.
package main
// #cgo LDFLAGS: -L. -llibrary
// #include "library-bridge.h"
import "C"
import "unsafe"
import "fmt"
type Foo struct {
ptr unsafe.Pointer
}
func NewFoo(value int) Foo {
var foo Foo
foo.ptr = C.LIB_NewFoo(C.int(value))
return foo
}
func (foo Foo) Free() {
C.LIB_DestroyFoo(foo.ptr)
}
func (foo Foo) value() int {
return int(C.LIB_FooValue(foo.ptr))
}
func main() {
foo := NewFoo(42)
defer foo.Free() // The Go analog to C++'s RAII
fmt.Println("[go]", foo.value())
}
Using the following Makefile
liblibrary.so: library.cpp library-bridge.cpp
clang++ -o liblibrary.so library.cpp library-bridge.cpp \
-std=c++17 -O3 -Wall -Wextra -fPIC -shared
I can run the example program as follows:
$ make
clang++ -o liblibrary.so library.cpp library-bridge.cpp \
-std=c++17 -O3 -Wall -Wextra -fPIC -shared
$ go run library.go
[c++ bridge] LIB_NewFoo(42)
[c++] Foo::Foo(42)
[c++ bridge] LIB_NewFoo(42) will return pointer 0x42002e0
[c++ bridge] LIB_FooValue(0x42002e0)
[c++] Foo::value() is 42
[go] 42
[c++ bridge] LIB_DestroyFoo(0x42002e0)
[c++] Foo::~Foo(42)
Important
The comments above import "C" in the go program are NOT OPTIONAL. You must put them exactly as shown so that cgo knows which header and library to load, in this case:
// #cgo LDFLAGS: -L. -llibrary
// #include "library-bridge.h"
import "C"
Link to GitHub repo with the full example.
Looks it's one of the early asked question about Golang . And same time answers to never update . During these three to four years , too many new libraries and blog post has been out . Below are the few links what I felt useful .
SWIG and Go
Calling C++ Code From Go With SWIG
On comparing languages, C++ and Go
GoForCPPProgrammers
There's talk about interoperability between C and Go when using the gcc Go compiler, gccgo. There are limitations both to the interoperability and the implemented feature set of Go when using gccgo, however (e.g., limited goroutines, no garbage collection).
You're walking on uncharted territory here. Here is the Go example for calling C code, perhaps you can do something like that after reading up on C++ name mangling and calling conventions, and lots of trial and error.
If you still feel like trying it, good luck.
You might need to add -lc++ to the LDFlags for Golang/CGo to recognize the need for the standard library.
The problem here is that a compliant implementation does not need to put your classes in a compile .cpp file. If the compiler can optimize out the existence of a class, so long as the program behaves the same way without it, then it can be omitted from the output executable.
C has a standardized binary interface. Therefore you'll be able to know that your functions are exported. But C++ has no such standard behind it.
Funny how many broader issues this announcement has dredged up. Dan Lyke had a very entertaining and thoughtful discussion on his website, Flutterby, about developing Interprocess Standards as a way of bootstrapping new languages (and other ramifications, but that's the one that is germane here).
This can be achieved using command cgo.
In essence
'If the import of "C" is immediately preceded by a comment, that comment, called the preamble, is used as a header when compiling the C parts of the package. For example:'
source:https://golang.org/cmd/cgo/
// #include <stdio.h>
// #include <errno.h>
import "C"