How Python can get binary data(char*) from C++ by SWIG?

后端 未结 3 828
忘掉有多难
忘掉有多难 2020-12-21 04:38

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.

For example:

e

3条回答
  •  难免孤独
    2020-12-21 05:07

    First of all, you should not use char * if you are dealing with binary data (swig thinks that they are normal strings). Instead you should use void *. swig provides a module named 'cdata.i' - you should include this in the interface definition file.

    Once you include this, it gives two functions - cdata() and memmove().

    • Given a void * and the length of the binary data, cdata() converts it into a string type of the target language.
    • memmove() does the reverse - given a string type, it will copy the contents of the string(including embedded null bytes) into the C void* type.

    Handling binary data becomes much simpler with this module. I hope this is what you need.

    example.i
    %module example
    %include "cdata.i"
    %{
    void *fun()
    {
            return "abc\0de";
    }
    %}
    
    test.py
    import example
    print example.cdata(example.fun(), 6)
    

提交回复
热议问题