也許有人知道,如何重寫getVersion以獲取 Python版本和legacyVersion作為函式的結果,而不是將它們作為輸入/輸出引數傳遞
class DeviceInterface {
public:
virtual uint32_t getVersion(uint8_t* version, uint8_t* legacyVersion ) = 0;
};
現在我在 SWIG 介面檔案中創建了額外的函式,但當前的實作只回傳一個引數而不是兩個。
%ignore DeviceInterface::getVersion( uint8_t* version, uint8_t* legacyVersion );
%extend DeviceInterface {
virtual char * getVersion() {
static uint8_t _v[200];
static uint8_t _lv[200];
$self->getVersion(_v, _lv);
return (char *)_lv;
}
};
更新
現在我使用@ignore和@extend功能。但我想有更優雅的方式。這是我作業的 SWIG 界面片段:
%extend DeviceInterface {
virtual PyObject *getVersion() {
static uint8_t _v[200];
static uint8_t _lv[200];
uint32_t libCode = $self->getVersion(_v, _lv);
return Py_BuildValue("(l,s,s)", libCode, (char *)_v, (char *)_lv);
}
};
uj5u.com熱心網友回復:
您可以定義自己的型別映射來處理輸出引數。在這種情況下,型別映射將所有 uint32_t*引數視為 200 位元組的輸出緩沖區。這是一個沒有錯誤檢查的最小示例。
%module test
%include <stdint.i>
// Require no input parameter. Just allocate a fixed-sized buffer.
%typemap(in,numinputs=0) uint8_t* %{
$1 = new uint8_t[200];
%}
// Free the temporary buffer when done converting the argument
%typemap(freearg) uint8_t* %{
delete [] $1;
%}
// On output, convert the buffer to a Python byte string
%typemap(argout) uint8_t* %{
$result = SWIG_Python_AppendOutput($result, PyBytes_FromString(reinterpret_cast<char*>($1)));
%}
// Example implementation
%inline %{
#include <stdint.h>
class DeviceInterface {
public:
virtual uint32_t getVersion(uint8_t* version, uint8_t* legacyVersion ) {
strcpy(reinterpret_cast<char*>(version),"1.0.0");
strcpy(reinterpret_cast<char*>(legacyVersion),"2.0.0");
return 0;
}
};
%}
輸出:
>>> import test
>>> d=test.DeviceInterface()
>>> d.getVersion()
[0, b'1.0.0', b'2.0.0']
請注意,輸出是回傳值和兩個輸出引數的串聯。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/402634.html
標籤:
上一篇:關于C中的演員表的困惑
下一篇:我在C中的結構鏈表有問題
