0

I have a C++ library that provides various classes for managing data. I have the source code for the library. I am trying to call a function of lda.cpp of this library from python using ctypes. This function in turn uses function from all other .cpp files in the library.

//lda.cpp
#include "model.h"
#include <stdio.h>
#include "lda.h"

int lda_est(double alpha, double beta) {
    model lda;
    if (lda.model_est(alpha, beta)) {
         return 1;
    }

    lda.estimate();

    return 0;
}

What i found out is that i need to use C++ wrappers declaring the functions as extern and then compile them to a .so file. My question is how should i make this wrapper file? And should I declare all the functions in the library as extern or only the one that I want to call from python?

J.J. Hakala
  • 6,136
  • 6
  • 27
  • 61
  • Your functions need to be declared like `int extern "C" lda_est(double alpha, double beta)`, see http://stackoverflow.com/a/7061012/5781248 – J.J. Hakala Jan 21 '16 at 06:23
  • 1
    If you are not happy with `extern C`, Then you might like to have look at `boost-python` or https://github.com/wjakob/pybind11 – dlmeetei Jan 21 '16 at 06:26

1 Answers1

0

ctypes is a tool to integrate existing libraries that you can't change. Since you have the sources and are willing to change them, you can as well write a Python module in C++, for which there are multiple toolkits like e.g. Boost.Python. In other words, @Deleisha is right, ctypes is the wrong tool for the job.

Note that you can still create a Python module from an existing library by wrapping functions and classes. Using a toolkit instead of extern "C" wrappers also still makes sense there. Firstly, it eases wrapping classes and secondly, you don't need an extern "C" wrapper in C++ and another ctypes wrapper in Python.

Ulrich Eckhardt
  • 16,572
  • 3
  • 28
  • 55