简体   繁体   English

如何从python将字符指针传递给C++ API?

[英]How to pass char pointer to C++ API from python?

I am trying to call the following C++ method from my python code:我正在尝试从我的 python 代码中调用以下 C++ 方法:

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.这是一个带有模拟 API 的通用示例。 In lib.cc :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:然后,在 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!'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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