Python如何通过SWIG从C ++获取二进制数据(char *)? [英] How Python can get binary data(char*) from C++ by SWIG?

查看:799
本文介绍了Python如何通过SWIG从C ++获取二进制数据(char *)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在SWIG使用Python中的C ++函数,现在我遇到了一个问题。
当我将一个char *从C ++传递给Python时,char *由Python修饰。

I am using C++ functions in Python by SWIG,and I met a problem now. When I pass a char * from C++ to Python, the char * is truncted by Python.

例如:

example.h:

example.h:

char * fun()
{
    return "abc\0de";
}

现在在Python中,我们调用
example.fun b $ b它只打印
abc
而不是
abc\0de
'\0'后面的数据被Python删除。

now in Python,we call example.fun() it only print "abc" instead of "abc\0de" the data behind '\0' is deleted by Python.

我想从C ++中的fun()获取所有的字符(它是一个二进制数据,可以包含'\0'),
和任何建议

I want to get all the chars(it is a binary data that can contains '\0') from fun() in C++, and any advise is appreciated

推荐答案

C / C ++字符串是NULL终止的,这意味着第一个 \0 字符表示字符串的结尾。

C/C++ strings are NULL-terminated which means that the first \0 character denotes the end of the string.

当一个函数返回指向这样一个字符串的指针时,调用者(在这种情况下是SWIG)如果第一个 \0 后有更多的数据,这就是为什么你只得到第一部分。

When a function returns a pointer to such a string, the caller (SWIG in this case) has no way of knowing if there is more data after the first \0 so that's why you only get the first part.

首先要做的是更改你的C函数不仅返回字符串,而且返回其长度。因为只有一个返回值,我们将使用指针参数。

So first thing to do is to change your C function to return not just the string but its length as well. Since there can be only one return value we'll use pointer arguments instead.

void fun(char** s, int *sz)
{
    *s = "abc\0de";
    *sz = 6;
}



SWIG文档建议使用 cstring.i 包装此类函数。

%cstring_output_allocate_size(parm, szparm, release)

阅读文档以了解如何使用它。

Read the docs to learn how to use it.

这篇关于Python如何通过SWIG从C ++获取二进制数据(char *)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆