簡體   English   中英

SWIG C / python和無符號char指針

[英]SWIG C/python and unsigned char pointers

我有一個函數形式

void f(unsigned char *out, const unsigned long long outlen,
       const unsigned char *in, const unsigned long long inlen);

當我嘗試使用它時:

data_in = ['a', 'b', 'c', 'd', 'e']
data_out = [0]*100
f(data_out, len(data_out), data_in, len(data_in))

(實際上,我想傳遞字節數組)

我得到類似的東西:

Traceback (most recent call last):
  File "xxxx/basic_test.py", line 6, in <module>
    f(data_out, len(data_out), data_in, len(data_in))
TypeError: in method 'f', argument 1 of type 'unsigned char *'

我嘗試了不同的方法來傳遞data_out(編碼,byterray,[0] * 100等),但是似乎沒有任何效果。

這應該如何工作?

以防萬一,這可能會產生一些影響,這是一個C函數,因此為了避免混亂,我將其包裝在一起

extern "C"
{
...
}

不幸的是我無法更改C代碼

嘗試改用unsigned char data[]

如果使用的是C ++,請嘗試通過STL中的String類傳入。

您的python字符串似乎與C函數的預期參數類型不兼容。 可能對您有幫助。 建議使用c_char_p來獲取正確的類型。 也就是說,如果您希望在不復制字符串的情況下執行此操作,則存在一些限制。

如果可以根據需要定義字符串或復制它,則可以使用ctypes,其中一種是c_ubyte

在手冊中可能很容易找到,但是這里

xxxx.h

#pragma once
extern "C" {
  void f(unsigned char *out, const unsigned long long outlen,
    const unsigned char *in, const unsigned long long inlen);
}

xxxx.cc

#include "xxxx.hh"

void f(unsigned char *out, const unsigned long long outlen,
       const unsigned char *in, const unsigned long long inlen) {
  // Really stupid - only writing a fixed output
  out[outlen-1] = (unsigned char) 57;
}

編譯使用

g++ -shared -fPIC -Wl,-soname,libxxxx.so -o libxxxx.so xxxx.o

在Python中,如下使用它

import ctypes

input = [0,1,2,3]
output = [0,0,0,0]
input = (ctypes.c_uint8 * 4)(*input)
output = (ctypes.c_uint8 * 4)(*output)

h = ctypes.cdll.LoadLibrary('./libxxxx.so')
h.f(output,4,input,4)

# Note how output[3] is 57 or chr(output[3]) is '9'

請參閱這篇文章,了解如何將字符串轉換為char數組,如何使用ctypes將python字符串對象轉換為c char *

謝謝你的回答。

我知道如何使用ctypes,但是我的問題是關於SWIG的,因為我也打算為其他語言生成包裝器。

有一些遺留代碼(類似C),無法修改,但它是更大的C ++ 11庫的一部分。 這意味着我可能會發現處理問題等。我不希望不修改要公開的功能的簽名。 它們unsigned char*的原因是因為這是原始數據。 不是典型的零終止char*字符串。 (您可以通過查看unsigned來得到提示)

我追求的干凈解決方案是給定一個功能

bool foo(unsigned char* data)
{
   ...
} 

編寫C ++包裝器(在某些情況下,我使用了基於模板的技巧)

bool bar(vector<unsigned char> &x)
{
   foo(x.data())
}

在我做的界面文件中

%include "std_vector.i"
namespace std {
  %template(ucharVector) vector<unsigned char>;
}
... include library, etc...

和Python:

data = lib.ucharVector([1, 2, 3, 4])
answer = lib.bar(data)

注意:關於const正確性,我避免在此答案中將其保持簡單。 但應予以考慮。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM