简体   繁体   中英

How to pass char pointer to C++ API from python?

I am trying to call the following C++ method from my python code:

TESS_API TessResultRenderer* TESS_CALL TessTextRendererCreate(const char* outputbase)
{
    return new TessTextRenderer(outputbase);
}

I'm having difficulty with how to pass the pointer to the method:

Is following the right way?

textRenderer = self.tesseract.TessTextRendererCreate(ctypes.c_char)

or should I be doing:

outputbase = ctypes.c_char * 512
textRenderer = self.tesseract.TessTextRendererCreate(ctypes.pointer(outputbase))

Doing above gives me error:

TypeError: _type_ must have storage info

You should be passing in a string.

For example:

self.tesseract.TessTextRendererCreate('/path/to/output/file/without/extension')

Here's a generalized example with a mock API. In lib.cc :

#include <iostream>

extern "C" {
  const char * foo (const char * input) {
    std::cout <<
      "The function 'foo' was called with the following "
      "input argument: '" << input << "'" << std::endl;

    return input;
  }
}

Compile the shared library using:

clang++ -fPIC -shared lib.cc -o lib.so

Then, in Python:

>>> from ctypes import cdll, c_char_p
>>> lib = cdll.LoadLibrary('./lib.so')
>>> lib.foo.restype = c_char_p
>>> result = lib.foo('Hello world!')
The function 'foo' was called with the following input argument: 'Hello world!'
>>> result
'Hello world!'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM