0

Situation

I am trying to write a python wrapper for an already existing C++ application. The C++ source code of the application is not available to me. What I do have is a header file zq_extapi.h and a library file zq_extapi.dll. The file zq_extapi.h contains the following:

#ifndef ZQ_EXTAPI_DECLS
#define ZQ_EXTAPI_DECLS
#endif

class ZQ_ExtAPI
{
protected:
    virtual ~ZQ_ExtAPI() {}

public:
    virtual const char* RunZQCommand(const char* str, int* res_code=(int*)0) = 0;

};

extern "C" ZQ_EXTAPI_DECLS
ZQ_ExtAPI* Open_ZQ_ExtAPI(int* err_code=0, int nargs=0, void** args=0);

Tried thus far

I've tried to write a python wrapper using ctypes:

import ctypes
lib = ctypes.cdll.LoadLibrary("zq_extapi.dll")

class ZQ_ExtAPI(object):
    def __init__(self):
        self.obj = lib.Open_ZQ_ExtAPI(ctypes.byref(err_code), 0)

    def RunZQCommand(self, command):
        # ??????

zq_ext_api_object = lib.Open_ZQ_ExtAPI(0, 0)

This code seems to be successful in initializing a C++ ZQ_ExtAPI object. Subsequently I'd like to execute the RunZQCommand of the created ZQ_ExtAPI object, but at this point I'm stuck.

Question

If I understand correctly, then it's not possible to call the RunZQCommand C++ method directly from a python ctypes wrapper because the method has no C-linkage. What additional code would I need in order to make to make the RunZQCommand C++ method callable from a python ctypes wrapper?

Note: if there's another easier way than ctypes to make a python wrapper for my C++ application, then I would be very interested in that as well.

Xukrao
  • 8,003
  • 5
  • 26
  • 52
  • 2
    You can't call C++ code because of C++ ABI (name mangling and the way objects are laid out in memory); see [this answer](https://stackoverflow.com/questions/1615813/how-to-use-c-classes-with-ctypes). You'll need to do a `C` interface if you still want to use ctypes or use something [that can generate the glue for you](https://stackoverflow.com/questions/145270/calling-c-c-from-python). – Neitsa Dec 22 '19 at 08:13
  • 1
    Once you have that C API, I highly recommend looking into Cython. It makes it easy to write really Pythonic interfaces. – Jonathon Reinhart Dec 22 '19 at 17:22

0 Answers0