You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用ctypes在Python中映射C结构体时遇类型错误求助

解决ctypes映射C结构体时的TypeError问题

问题重现

C代码(c_file.c)

#include<stdio.h>

struct SomeStructure{
    int age;
    char c;
    char* name;
};

double someFunction(struct SomeStructure *s){
    printf("My age is %d and my c is %s and finally name is %s", s->age, s->c, s->name);
    return 42;
}

编译命令

gcc -fPIC -shared -o clibrary.so c_file.c

Python代码(py_file.py)

import ctypes

clibrary = ctypes.CDLL("./clibrary.so")

class SomeStructure(ctypes.Structure):
    _fields_ = [
        ('age', ctypes.c_int),
        ('c', ctypes.c_char),
        ('name', ctypes.c_char_p)
    ]

clibrary.someFunction.restype = ctypes.c_double
clibrary.someFunction.argtypes = [ctypes.POINTER(SomeStructure)]

obj = SomeStructure(13, 'm', b"Jo")
clibrary.someFunction(ctypes.byref(obj))

错误信息

obj = SomeStructure(13, 'm', b"Jo")
TypeError: one character bytes, bytearray or integer expected

解决步骤

  • 修正char类型的赋值错误
    ctypes.c_char类型要求传入单字节对象(比如b'm')或者对应的ASCII整数(比如109),不能直接传字符串'm'。修改结构体实例化代码:

    obj = SomeStructure(13, b'm', b"Jo")
    # 或者用ASCII整数:obj = SomeStructure(13, 109, b"Jo")
    
  • 修复C代码中的printf格式符错误
    C代码里s->c是char类型,应该用%c格式符,而不是%s(%s用于字符串指针),否则会导致未定义行为(程序崩溃或乱码)。修改后的C函数:

    double someFunction(struct SomeStructure *s){
        printf("My age is %d and my c is %c and finally name is %s", s->age, s->c, s->name);
        return 42;
    }
    
  • 重新编译并运行
    重新执行编译命令生成新的共享库,再运行Python代码即可正常输出:

    My age is 13 and my c is m and finally name is Jo
    

内容的提问来源于stack exchange,提问作者Avv

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 21:05:25