如何将 char 指针从 python 传递给 C++ API?
How to pass char pointer to C++ API from python?
我正在尝试从我的 python 代码中调用以下 C++ 方法:
TESS_API TessResultRenderer* TESS_CALL TessTextRendererCreate(const char* outputbase)
{
return new TessTextRenderer(outputbase);
}
我对如何将指针传递给方法有困难:
走的路对吗?
textRenderer = self.tesseract.TessTextRendererCreate(ctypes.c_char)
或者我应该这样做:
outputbase = ctypes.c_char * 512
textRenderer = self.tesseract.TessTextRendererCreate(ctypes.pointer(outputbase))
执行上述操作会出现错误:
TypeError: _type_ must have storage info
您应该传入一个字符串。
例如:
self.tesseract.TessTextRendererCreate('/path/to/output/file/without/extension')
这是一个带有模拟 API 的通用示例。在 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;
}
}
使用以下方法编译共享库:
clang++ -fPIC -shared lib.cc -o lib.so
然后,在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!'
我正在尝试从我的 python 代码中调用以下 C++ 方法:
TESS_API TessResultRenderer* TESS_CALL TessTextRendererCreate(const char* outputbase)
{
return new TessTextRenderer(outputbase);
}
我对如何将指针传递给方法有困难:
走的路对吗?
textRenderer = self.tesseract.TessTextRendererCreate(ctypes.c_char)
或者我应该这样做:
outputbase = ctypes.c_char * 512
textRenderer = self.tesseract.TessTextRendererCreate(ctypes.pointer(outputbase))
执行上述操作会出现错误:
TypeError: _type_ must have storage info
您应该传入一个字符串。
例如:
self.tesseract.TessTextRendererCreate('/path/to/output/file/without/extension')
这是一个带有模拟 API 的通用示例。在 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;
}
}
使用以下方法编译共享库:
clang++ -fPIC -shared lib.cc -o lib.so
然后,在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!'