c++ - 在 SWIG 中将可变 char * 传递给 Python

标签 c++ python swig

我有一个需要在 Python 中实现的纯虚类,以便从 C++ 框架中回调它。

文件 example.h :

/** Abstract reader to be implemented */
class Reader {
public:
    /// Read maximum of `n` bytes into `c`
    virtual int read(char *c, int n) = 0;
    virtual ~Reader() {}
};

void test(Reader &r);

文件 example.cpp

#include "example.h"

void test(Reader &r) {
    char buf[] = {0, 0, 0};
    r.read(buf, 3);
}

SWIG 接口(interface):

%module(directors="1") example
%{
#include "example.h"
%}

%feature("director") Reader;
%include "example.h"

Python测试代码:

import example
class ReaderImpl(example.Reader):
    def __init__(self):
        example.Reader.__init__(self)

    def read(self, c, n):
        ''' Demo impl '''
        print type(c)
        return 0

example.test(ReaderImpl())

后者将打印 <type 'str'>这对我没有用,因为我应该写入缓冲区。所以,问题是:有没有办法告诉 SWIG 我宁愿为 char * 写一些可写的东西? ,也许,像 ctypes 数组?

最佳答案

查看来自 http://www.swig.org/Doc1.3/Python.html#Python_nn4831.7.4 String handling 部分

这个变化并不是那么微不足道,因为字符串的长度是可以改变的。如果您真的想要一个数组或类似的东西,请查看有关如何定义您自己的类型映射的文档。

考虑到 python 映射的开销,您最好只从 read() 返回一个字符串(更简单的代码)。

关于c++ - 在 SWIG 中将可变 char * 传递给 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20262445/

相关文章:

python - SWIG Python C/C++。结果模块是空的,没有错误

c++ - 行编辑setText函数Qt

python - SWIG 和 Python3 导入错误

c++ - C++中的动态分配列表

python - 使用 odo 和 SQLAlchemy 将 CSV 加载到 MySQL

python - 我如何更改此激光测距仪 python 代码以检测绿点而不是红点?

Python:如何对两列进行分组?

java - SWIG 指针和 Java 数组

c++ - 服务器应用程序框架(最好使用 BOOST C++)

c++ - "clean"规则在 Makefile 中不存在,但无论如何 make clean 都会产生一些东西