ctypes c_uint32从python错误地传递到Cpp

如何解决ctypes c_uint32从python错误地传递到Cpp

我正在使用带有ctypes的python来调用C so文件。

C结构为:

typedef struct {
uint32_t var1;
uint32_t var2;
uint32_t var3;
uint8_t var4;
uint8_t var5
} struct1;


If I call C code where I set the variables of var1 to 0x050A,var2 to 0x102 and var3 to 0x203 build it and print out the values everything works perfectly.

in C
static struct1 mstruct;  
mstruct.var1=1290  
mstruct.var2=258  
mstruct.var3=515  

然后我调用一个c.so文件,打印出传递给它的结构的值。

printf("var1 %lx\n",mstruct.var1) # var1 050A  
printf("var2 %lx\n",mstruct.var2) # var2 102  
printf("var3 %lx\n",mstruct.var3) # var3 203  

请注意,如果我只使用x而不是lx,它将无法构建并给出错误。
但是当从C调用时,所有内容都能正确打印
var1 050A
var2 102
var3 203

现在,如果我使用python初始化并调用相同的结构,则我将类定义为:

class struct1(ctypes.Structure):
   _fields_=[
             ('var1',ctypes.c_uint32),('var2',('var3',('var4',ctypes.c_uint8),('var5',ctypes.c_uint8)]

   def __init__(self):
         self.var1=1290
         self.var2=258
         self.var3=515

if __name__=='__main__':
    mstruct=struct1()
    print('var1 {}  type {}'.format(mstruct.var1,type(mstruct.var1)))
    clib=ctypes.CDLL('csofile.so')
    c_rtn=clib.print_c_struct(ctypes.byref(mstruct))

Var1值正确,并且类型被打印为类'int'(不是ctypes uint32)。
并在C.so文件中打印出来
var1 1020000050a
var2 50a00000203
var3 20300000102

Var1的最低16位是正确的值。中间的16位填充有正确的零。但是在var1中应该有var 2应该有高32位。然后Var2从Var3中的值开始。

似乎有一个不匹配的地方,例如我的python并没有真正将其定义为32位,但是奇怪的是C实际将其读取为64位,我不知道这种情况如何。由于C结构将其定义为32位,因此我希望它仅占用32位,因此以某种方式它会通过python查看64位。

如果我将所有内容都更改为int,那么它在我的演示应用程序中就可以正常工作,但是真正的C.so文件是由其他人创建的,因此我每两天就会得到一个新文件,因此我试图避免每次更改它。 >

当我在 init 中设置值时,我还尝试了强制类型转换,以为可能是我覆盖了类型,但似乎没有任何改变。

self.var1=(ctypes_c_uint32)(1290)

任何帮助将不胜感激。

标题:

#include <stdint.h>


typedef struct{
  uint32_t first;
  uint32_t second;
  int *marray;

} my_struct;

int call_c_function(int var1,int *var2,my_struct *mstruct );

C文件

#include <stdio.h>
#include <memory.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include "c_header.h"


int call_c_function(int var1,my_struct *mstruct ){
  
  
  printf("var1 %d \n",var1);
  printf("var2 %d \n",*var2);
  
  printf("mystruct first %ld \n",mstruct->first);
  printf("mystruct second %ld \n",mstruct->second);

  int *array_ptr;
  array_ptr = mstruct->marray;
  printf("C ADDR struct %p \n",mstruct);
  printf("C ADDR of pointer array_ptr %p \n",&array_ptr);
  printf("C ADDR  stored at array_ptr %p I need Python to match this!\n",array_ptr);
  printf("Value in Memory it points to %d \n",*array_ptr);
  
  printf("size of c int %ld\n",sizeof(int));
  
  for (int i=0;i<8;i++){
    printf(" %d ",array_ptr[i]);
    array_ptr[i]=8-i;
    }
    
printf("\n ");

  return 0;
}

使用g ++ -fPIC -shared -o clib.so c_file.cpp进行编译 还有Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 18 13:16:52 2020

@author: kevin.johnson
"""
import ctypes as ctypes
import struct as struct



so_file='./clib.so'


class my_struct(ctypes.Structure):
    _fields_=[
              ('first',('second',('marray',ctypes.POINTER(ctypes.c_int))]
    def __init__(self,ma):
         self.first=1290
         self.second=258
         self.marray = ma
         
def so_attr(sofile):
    from subprocess import Popen,PIPE
    
    out = Popen(args='nm ./{}'.format(sofile),shell=True,stdout=PIPE).communicate()[0].decode("utf-8")

    attrs=[i.split(" ")[-1].replace("\r","")
        for i in out.split("\n") if " T " in i]
    functions = [i for i in attrs if hasattr(ctypes.CDLL(sofile),i)]
    print (functions)    

def arr2list(inp,length):
    outp=[inp[i] for i in range(length)]                
    
    return outp
    
if __name__ == '__main__':
    
    if 0:
        so_attr(so_file)
    else:
        mn = [i for i in range(8)]
        ms = ctypes.c_int*8
        ma = ms(*mn)
        print(type(ma))
        ma_p = ctypes.cast(ma,ctypes.POINTER(ctypes.c_int))
        ma_byref = ctypes.byref(ma)
    
        mstruct_inst=my_struct(ma_p)
        
        print ('size of python int {} '.format(ctypes.sizeof(ma)/len(ma)))
        
        print(mstruct_inst)
        print('var1 {} type {}'.format(mstruct_inst.first,type(mstruct_inst.first)))

        
        var1=ctypes.c_int(5)
        var2=ctypes.c_int(6)
        
        print(arr2list(ma,8))
        
        clib=ctypes.CDLL(so_file)
        print('ADDRESS: {}'.format(ctypes.byref(mstruct_inst)))
        print('by ref ma: {} I Need C to match this'.format(ma_byref))
        print('map: {}'.format(ma_p))
        print('map2: {}'.format(ctypes.cast(ctypes.byref(ma),ctypes.POINTER(ctypes.c_int))))
        
        funct_int=clib._Z15call_c_functioniPiP9my_struct(var1,ctypes.byref(var2),ctypes.byref(mstruct_inst))
    
        print ('C Function return {} '.format(funct_int))
        
        print(arr2list(ma,8))
    
    
    print('done')

解决方法

您系统上的

long是64位,如printf("%lx")打印64位整数所显示。正如我在注释中看到的那样,您的C代码uint32_t被定义为unsigned long,在该系统上是不正确的。

您的系统应具有stdint.h标头,该标头为您的操作系统正确定义了uint32_t

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-