0

I'm using ctypes in order send the request to C++ application. For this I created the same structure in Python and C header file like this

C

typedef struct {
   int msg_id;
   unsigned char name[20];
} c_struct;

Python

from ctypes import *

class py_struct(BigEndianStructure):
    def __init__(self):
        BigEndianStructure.__init__(self)

    _fields_ = [('msg_id', c_int), ('name', c_char*20)]


.....

self.name = StringVar()
Entry(self, textvariable=self.name)

.....

def send(self):
   cmd = py_struct()
   cmd.name = self.name.get()

It doesn't work and raises a TypeError exception.

another code also doesn't work for me like this

name = (c_char*20)(self.name.get())
cmd.name = name

or

name = (c_char*20)(self.name.get().encode('utf-8'))
cmd.name = name

I've tried many ways to convert the Python string object with ctypes.

  • ctypes.c_char_p
  • ctypes.create_string_buffer

Can someone help me to convert a string object to c_char*20 array? Thanks in advance.

2 Answers 2

1

I've found the solution

name = bytes(self.name.get().encode('utf-8'))
cmd.name = name
Sign up to request clarification or add additional context in comments.

1 Comment

.encode() returns a bytes object and defaults to utf-8 so cmd.name = self.name.get().encode() should be sufficient.
0

Here's a reproducible example. .encode() should be all that's needed:

from tkinter import *
from ctypes import *

class Demo(Structure):
    _fields_ = [('name',c_char*20)]

root = Tk()
s = StringVar()
s.set('Hello, world!')

d = Demo()
d.name = s.get().encode()
print(d.name)

Output:

b'Hello, world!'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.