簡體   English   中英

如何使用Swig將未簽名的char *轉換為Python列表?

[英]How to convert unsigned char* to Python list using Swig?

我有這樣的C ++類方法:

class BinaryData
{
public:
    ...
    void serialize(unsigned char* buf) const;
};

serialize函數只是將二進制數據作為unsigned char* 我使用SWIG包裝此類。 我想在python中將二進制數據讀取為byte arrayint array

Python代碼:

buf = [1] * 1000;
binData.serialize(buf);

但是發生了無法轉換為unsigned char*異常。 如何在python中調用此函數?

最簡單的方法是在Python中進行轉換:

buf = [1] * 1000;
binData.serialize(''.join(buf));

可以開箱即用,但是根據Python用戶的期望可能不佳。 您可以在Python代碼中使用SWIG來解決,例如:

%feature("shadow") BinaryData::serialize(unsigned char *) %{
def serialize(*args):
    #do something before
    args = (args[0], ''.join(args[1]))
    $action
    #do something after
%}

或在生成的接口代碼內,例如使用緩沖區協議

%typemap(in) unsigned char *buf %{
    //    use PyObject_CheckBuffer and
    //    PyObject_GetBuffer to work with the underlying buffer
    // AND/OR
    //    use PyIter_Check and
    //    PyObject_GetIter
%}

根據您偏愛的編程語言和其他特定於情況的約束,您更願意這樣做。

暫無
暫無

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

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