4

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

1 Answer 1

4

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!'
Sign up to request clarification or add additional context in comments.

2 Comments

Passing in a string worked for me! however, the calls to different methods is failing. I asked a related question and was wondering if you can help stackoverflow.com/questions/36871072/…
Note that a string should only be directly passed for const char *. If it's not const, use ctypes.create_string_buffer('initial value, or use an integer size'). Python strings are semantically immutable, and CPython depends on this to allow interning various strings in code objects and attribute names. If an interned string gets mutated, it's not just a matter of data corruption but also breaks attribute access and dict lookup if the string is a dict key.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.