我需要某種方法將unit8_t陣列轉換為char陣列或char * string 以在 Python 端創建 Job 物件并在從 C 端獲取物件后列印它的欄位。SWIG 是否支持自定義訪問器函式(即 get/set)或“magic” arg 轉換?
我嘗試了@ignore功能來跳過識別符號和名稱成員的處理并添加%inline訪問器函式,但沒有結果。
在 Python 中:
job = someFuncInCppCode()
print("Identifier: " job.identifier)
呼叫 Python 列印時出錯:
Execution error: can only concatenate str (not "SwigPyObject") to str
C 頭檔案
struct Job
{
static const int MaxIdentifierLength = 20;
static const int MaxNameLength = 40;
uint8_t identifier[MaxIdentifierLength];
uint8_t name[MaxNameLength];
uint32_t status;
};
SWIG 自動生成的代碼:
SWIGINTERN PyObject *_wrap_Job_identifier_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
PyObject *resultobj = 0;
Job *arg1 = (Job *) 0 ;
void *argp1 = 0 ;
int res1 = 0 ;
PyObject *swig_obj[1] ;
uint8_t *result = 0 ;
if (!args) SWIG_fail;
swig_obj[0] = args;
res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_Xrite__Device_Cpp__Topaz__Job, 0 | 0 );
if (!SWIG_IsOK(res1)) {
SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Job_identifier_get" "', argument " "1"" of type '" "Job *""'");
}
arg1 = reinterpret_cast<Job * >(argp1);
result = (uint8_t *)(uint8_t *) ((arg1)->identifier);
resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_unsigned_char, 0 | 0 );
return resultobj;
fail:
return NULL;
}
uj5u.com熱心網友回復:
一種方法是為該陣列型別定義輸出型別映射。見Typemaps陣列中SWIG檔案。例子:
測驗檔案
%module test
%include <stdint.i>
// Convert uint8_t array assumed to be a null-terminated string.
%typemap(out) uint8_t[ANY] %{
$result = PyBytes_FromString(reinterpret_cast<char*>($1));
%}
%inline %{
#include <stdint.h>
struct Job
{
static const int MaxIdentifierLength = 20;
static const int MaxNameLength = 40;
uint8_t identifier[MaxIdentifierLength];
uint8_t name[MaxNameLength];
uint32_t status;
};
// test function
Job func() {
return {"hello","world",5};
}
%}
演示:
>>> import test
>>> j=test.func()
>>> j.name
b'world'
>>> j.identifier
b'hello'
>>> j.status
5
如果您希望陣列中的每個位元組都可見,請改用此型別映射:
%typemap(out) uint8_t[ANY] %{
$result = PyBytes_FromStringAndSize(reinterpret_cast<char*>($1), $1_dim0);
%}
演示:
>>> import test
>>> j=test.func()
>>> j.identifier
b'hello\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/404660.html
標籤:
上一篇:我可以在python中通過matplotlib制作帶有字串標簽的散點圖嗎?
下一篇:在C中重新分配多維字符陣列的值
