簡體   English   中英

使用SWIG在c ++ Python包裝的類中用二進制數據填充char *

[英]Fill char* with binary data in a c++ Python wrapped class with SWIG

我已經用swig包裝了一個c ++類供python使用。 我的課是這樣的:

public class DataHolder
{
public:
     char* BinaryData;
     long Length;
}

public class MyProcessor
{
public:
    int process(DataHolder& holder)
    {
          holder.BinaryData = assign some binary data;
          holder.Length = 1024;
    }
}

我想要的是python這樣的東西:

import Module
from Module import *

proc = MyProcessor();
holder = DataHolder();

proc.process(holder);

#use holder.BinaryData to, for example, print

任何幫助將不勝感激,非常感謝!

您的示例C ++代碼不太合法(它看起來更像Java!),但是一旦我解決了這個問題,並為process添加了一些實際的東西,就可以按照您的希望包裝它。

與我以前的答案相比,主要的變化是長度是從類內部讀取的,而不是在容器上調用方法的結果。 這有點丑陋,因為我不得不對C ++“ this”對象的名稱進行硬編碼, $self引用了Python對象。 因此,我將類型圖僅在確定其合法且正確的有限情況下應用。

所以我的最終接口文件最終看起來像:

%module test

%typemap(out) char *DataHolder::BinaryData {
  Py_buffer *buf=(Py_buffer*)malloc(sizeof *buf);
  if (PyBuffer_FillInfo(buf, NULL, $1, arg1->Length, true, PyBUF_ND)) {
    // Error, handle
  }
  $result = PyMemoryView_FromBuffer(buf);
}

%inline %{
class DataHolder
{
public:
     char* BinaryData;
     long Length;
};

class MyProcessor
{
public:
    int process(DataHolder& holder)
    {
          static char val[] = "Hello\0Binary\0World\n!";
          holder.BinaryData = val;
          holder.Length = sizeof val;
          return 0;
    }
};
%}

我測試過的:

from test import *
proc = MyProcessor()
holder = DataHolder()

proc.process(holder)

data = holder.BinaryData
print(repr(data))
print(data.tobytes())

我在這里以Python3為目標,但完全相同的代碼也適用於Python 2.7。 當編譯並運行時,給出了:

swig2.0 -c++ -Wall -py3 -python test.i
g++ -Wall  -shared -o _test.so test_wrap.cxx -I/usr/include/python3.4
python3 run.py
<memory at 0xb7271f9c>
b'Hello\x00Binary\x00World\n!\x00'

暫無
暫無

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

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