我有一个C dll,它以包含十六进制值的未签名char *形式返回PDF文件。如何使用ctypes检索此数组并将其保存到“挖掘” PDF文件中?

例如,在C中,我这样做:

unsigned char* manual = getPluginManualAsPDF(mPlugin);
long nrOfBytes        = getPluginManualNrOfBytes(mPlugin);

string tempFile(mtk::JoinPath(getTempFolder(getRRHandleFromPlugin(mPlugin)), "AddNoisePluginDoc.pdf"));
ofstream temp(tempFile.c_str(), std::ios::binary);

long byteNr = 0;
while (byteNr < nrOfBytes)
{
    temp<< manual[byteNr];
    byteNr++;
}

temp.close();

    //Spanw an external pdf reader
    ShellExecute(Handle, "open", tempFile.c_str(), NULL, NULL,SW_SHOWNORMAL) ;
}

我正在尝试通过CTypes访问相同的函数(getPluginManualAsPDF和getPluginManualNrOfBytes),即
rrpLib.getPluginManualAsPDF.restype = c_buffer
def getPluginManualAsPDF(pluginHandle):
    return rrpLib.getPluginManualAsPDF(pluginHandle)

def getPluginManualNrOfBytes(pluginHandle):
    return rrpLib.getPluginManualNrOfBytes(pluginHandle)

但是有返回getPluginManualAsPDF()函数的问题。任何帮助表示赞赏。

最佳答案

假设您的getPluginManualAsPDFgetPluginManualNrOfBytes具有以下原型(prototype):

/* FIXME: the type of `mPlugin` isn't clear, is it void * ? */

unsigned char * getPluginManualAsPDF(void *mPlugin) {
  static unsigned char manual[] = {1, 2, 3};
  return manual;
}

long getPluginManualNrOfBytes(void *mPlugin) {
  return 12345;
}

您可以使用以下两个函数来调用:
from ctypes import *

rrpLib = cdll.rrpLib # or windll if it use STDCALL

getPluginManualAsPDF = rrpLib.getPluginManualAsPDF
getPluginManualAsPDF.restype = POINTER(c_ubyte)
getPluginManualAsPDF.argtypes = [c_void_p]

getPluginManualNrOfBytes = rrpLib.getPluginManualNrOfBytes
getPluginManualNrOfBytes.restype = c_long
getPluginManualNrOfBytes.argtypes = [c_void_p]

例如:
# gcc -Wall rrpLib.c -shared -o rrpLib.dll
# python
>>> from ctypes import *
>>>
>>> rrpLib = cdll.rrpLib # or windll if it uses STDCALL
>>>
>>> getPluginManualAsPDF = rrpLib.getPluginManualAsPDF
>>> getPluginManualAsPDF.restype = POINTER(c_ubyte)
>>> getPluginManualAsPDF.argtypes = [c_void_p]
>>>
>>> getPluginManualNrOfBytes = rrpLib.getPluginManualNrOfBytes
>>> getPluginManualNrOfBytes.restype = c_long
>>> getPluginManualNrOfBytes.argtypes = [c_void_p]
>>>
>>> getPluginManualAsPDF(None)[0]
1
>>> getPluginManualAsPDF(None)[1]
2
>>> getPluginManualAsPDF(None)[2]
3
>>>
>>>
>>> ptr = getPluginManualAsPDF(None)
>>> manual = cast(ptr, POINTER(c_ubyte * 3))[0]
>>> manual
<__main__.c_ubyte_Array_3 object at 0x017801C0>
>>> open('out.txt', 'wb').write(bytearray(manual))
>>> open('out.txt').read()
'\x01\x02\x03'
>>>
>>>
>>> getPluginManualNrOfBytes(None)
12345
>>>

10-06 00:01