Converting python string object to c char* using ctypes

后端 未结 3 1534
孤街浪徒
孤街浪徒 2020-12-29 23:49

I am trying to send 2 strings from Python (3.2) to C using ctypes. This is a small part of my project on my Raspberry Pi. To test if the C function received the strings corr

相关标签:
3条回答
  • 2020-12-30 00:30

    Have you considered using SWIG? I haven't tried it myself but here's what it would look like, without changing your C source:

    /*mymodule.i*/
    
    %module mymodule
    extern void my_c_function(const char* str1, const char* str2);
    

    This would make your Python source as simple as (skipping compilation):

    import mymodule
    
    string1 = "my string 1"
    string2 = "my string 2"
    my_c_function(string1, string2)
    

    Note I'm not certain .encode('utf-8') is necessary if your source file is already UTF-8.

    0 讨论(0)
  • 2020-12-30 00:36

    Thanks to Eryksun the solution:

    Python code

    string1 = "my string 1"
    string2 = "my string 2"
    
    # create byte objects from the strings
    b_string1 = string1.encode('utf-8')
    b_string2 = string2.encode('utf-8')
    
    # send strings to c function
    my_c_function.argtypes = [ctypes.c_char_p, ctypes.char_p]
    my_c_function(b_string1, b_string2)
    
    0 讨论(0)
  • 2020-12-30 00:55

    I think you just need to use c_char_p() instead of create_string_buffer().

    string1 = "my string 1"
    string2 = "my string 2"
    
    # create byte objects from the strings
    b_string1 = string1.encode('utf-8')
    b_string2 = string2.encode('utf-8')
    
    # send strings to c function
    my_c_function(ctypes.c_char_p(b_string1),
                  ctypes.c_char_p(b_string2))
    

    If you need mutable strings then use create_string_buffer() and cast those to c_char_p using ctypes.cast().

    0 讨论(0)
提交回复
热议问题