最近研究人脸识别,需要用python调用so动态库,涉及到c/c++中的指针字符串转Python的bytes对象的问题。
按照ctypes的文档,直观方式是先创建对应的类型数组,再将指针取地址一一赋值:

from ctypes import *
  
p=(c_char * )()
for i in range():
p[i] = i
 
b=bytes(bytearray(p))
print(b)

from ctypes import * p=(c_char * 10)() for i in range(10): p[i] = i b=bytes(bytearray(p)) print(b)

搜寻了各种资料,都未能找到更好的。。。直到ctypes.string_at

_string_at = PYFUNCTYPE(py_object, c_void_p, c_int)(_string_at_addr)
def string_at(ptr, size=-):
"""string_at(addr[, size]) -> string
 
Return the string at addr."""
return _string_at(ptr, size)

_string_at = PYFUNCTYPE(py_object, c_void_p, c_int)(_string_at_addr) def string_at(ptr, size=-1): """string_at(addr[, size]) -> string Return the string at addr.""" return _string_at(ptr, size)

于是char*转bytes可以直接用string_at方法,传入指针地址,以及字符串长度即可。

同样的问题,bytes对象需要传给c/c++代码。。。
直观方式同样是创建char数组array,拷贝bytes之后,再用cast强制转换成c_char_p

from ctypes import * 
 
p=(c_char * )()
for i in range():
p[i] = i
 
m=cast(p, c_char_p)
print(m)

from ctypes import * p=(c_char * 10)() for i in range(10): p[i] = i m=cast(p, c_char_p) print(m)

比较奇葩的是cast得到的对象,如果我们直接用bytes对象cast。。。

from ctypes import * 
 
b=b'0123456789'
m=cast(p, c_char_p)
print(m)

from ctypes import * b=b'0123456789' m=cast(p, c_char_p) print(m)

吼吼,奇迹出现了,bytes对象cast成了char*指针。。。用string_at转换看看

string_at(m)

string_at(m)

总结一下:
1、bytes基于Buffer Protocol,查看其c实现https://hg.python.org/cpython/file/3.4/Objects/bytesobject.c
2、string_as的c代码https://hg.python.org/cpython/file/3717b1481d1b/Modules/_ctypes/_ctypes.c

static PyObject *
string_at(const char *ptr, int size)
{
if (size == -)
return PyString_FromString(ptr);
return PyString_FromStringAndSize(ptr, size);
}

static PyObject * string_at(const char *ptr, int size) { if (size == -1) return PyString_FromString(ptr); return PyString_FromStringAndSize(ptr, size); }

3、cast的c代码同样在_ctypes.c(https://hg.python.org/cpython/file/3717b1481d1b/Modules/_ctypes/_ctypes.c)

static PyObject *
cast(void *ptr, PyObject *src, PyObject *ctype)
{
CDataObject *result;
if ( == cast_check_pointertype(ctype))
return NULL;
result = (CDataObject *)PyObject_CallFunctionObjArgs(ctype, NULL);
if (result == NULL)
return NULL;
 
/*
The casted objects '_objects' member:
 
It must certainly contain the source objects one.
It must contain the source object itself.
*/
if (CDataObject_Check(src)) {
CDataObject *obj = (CDataObject *)src;
/* CData_GetContainer will initialize src.b_objects, we need
this so it can be shared */
CData_GetContainer(obj);
/* But we need a dictionary! */
if (obj->b_objects == Py_None) {
Py_DECREF(Py_None);
obj->b_objects = PyDict_New();
if (obj->b_objects == NULL)
goto failed;
}
Py_XINCREF(obj->b_objects);
result->b_objects = obj->b_objects;
if (result->b_objects && PyDict_Check(result->b_objects)) {
PyObject *index;
int rc;
index = PyLong_FromVoidPtr((void *)src);
if (index == NULL)
goto failed;
rc = PyDict_SetItem(result->b_objects, index, src);
Py_DECREF(index);
if (rc == -)
goto failed;
}
}
/* Should we assert that result is a pointer type? */
memcpy(result->b_ptr, &ptr, sizeof(void *));
return (PyObject *)result;
 
failed:
Py_DECREF(result);
return NULL;
}

static PyObject * cast(void *ptr, PyObject *src, PyObject *ctype) { CDataObject *result; if (0 == cast_check_pointertype(ctype)) return NULL; result = (CDataObject *)PyObject_CallFunctionObjArgs(ctype, NULL); if (result == NULL) return NULL; /* The casted objects '_objects' member: It must certainly contain the source objects one. It must contain the source object itself. */ if (CDataObject_Check(src)) { CDataObject *obj = (CDataObject *)src; /* CData_GetContainer will initialize src.b_objects, we need this so it can be shared */ CData_GetContainer(obj); /* But we need a dictionary! */ if (obj->b_objects == Py_None) { Py_DECREF(Py_None); obj->b_objects = PyDict_New(); if (obj->b_objects == NULL) goto failed; } Py_XINCREF(obj->b_objects); result->b_objects = obj->b_objects; if (result->b_objects && PyDict_Check(result->b_objects)) { PyObject *index; int rc; index = PyLong_FromVoidPtr((void *)src); if (index == NULL) goto failed; rc = PyDict_SetItem(result->b_objects, index, src); Py_DECREF(index); if (rc == -1) goto failed; } } /* Should we assert that result is a pointer type? */ memcpy(result->b_ptr, &ptr, sizeof(void *)); return (PyObject *)result; failed: Py_DECREF(result); return NULL; }

[转] python关于ctypes使用char指针与bytes相互转换的问题的更多相关文章

  1. 初始化char指针--赋值和strcpy() 本质区别【转】

    原文地址:http://hi.baidu.com/todaygoodhj/item/0500b341bf2832e3bdf45180 使用常量字符串初始化char指针,或者使用strcpy复制,从语法 ...

  2. char[]数组与char *指针的区别

    char[]数组与char *指针的区别 问题描述 虽然很久之前有看过关于char指针和char数组的区别,但是当时没有系统的整理,到现在频繁遇到,在string,char[], char *中迷失了 ...

  3. char指针

    1.在C语言中,没有字符串类型,因此使用char指针表示字符串. 2.那么问题来了,使用char* 表示字符串,到哪里是结尾呢?因此需要一个特殊的字符作为哨兵,类似迭代器中的end(),这个哨兵就是' ...

  4. char数组与char指针

    1.以字符串形式出现的,编译器会在结尾自动添加\0,思考,为什么? 存在的C语言方法,如strlen(s),计算字符串的长度,其中s指针.strlen要计算字符串长度,必须知道哪里是结尾,因此使用\0 ...

  5. C: 当字符数组首指针转化成char *指针,sizeof(*ptr)不为array的size

    #include <stdio.h> #include <string.h> int main() { char a[10] = "\0"; char *p ...

  6. char 指针如何判断字符串需要输出长度

    先上代码: #include <stdio.h> #include <string.h> ] = "; int func1(const char *ip) { pri ...

  7. C++中将对象this转换成unsigned char指针

    示例程序 // ---CodeBlob.h--- #ifndef CODEBLOB_H_ #define CODEBLOB_H_ class CodeBlob { private: const cha ...

  8. Java之byte、char和String类型相互转换

    package basictype; /** * byte.char和String类型相互转换 */ public class CHJavaType { public static void main ...

  9. python pip 'nonetype' object has no attribute 'bytes'

    python pip 'nonetype' object has no attribute 'bytes' 更新 pip for Windows : python -m pip install -U ...

随机推荐

  1. P1012拼数

    这是一道字符串的普及—的题. 输入几组数字,怎样组合起来才可以使最后结果最大.一开始这道题类似于那道删数问题,每次删除递增序列的最后一位,达到最小.而这个题我也是想到了贪心做法,于是想逐位判断,让在前 ...

  2. Intellij IDEA奇巧妙计(不停更新)

    1,在pom.xml文件中,Ctrl+Shift+Alt+U打开Manven依赖视图 2,Alt+7 查看类里面方法,变量等结构 3, Shift+Esc 收缩编译提示框 4, ctrl+r 替换本页 ...

  3. 安装最新版Elasticsearch报错

    1 问题:ERROR: bootstrap checks failed max file descriptors [4096] for elasticsearch process likely too ...

  4. 深入了解RabbitMQ工作原理及简单使用

    深入了解RabbitMQ工作原理及简单使用 RabbitMQ系列文章 RabbitMQ在Ubuntu上的环境搭建 深入了解RabbitMQ工作原理及简单使用 RabbitMQ交换器Exchange介绍 ...

  5. Vue 中如何定义全局的变量和常量

    Vue 中如何定义全局的变量和常量 我想要定义一个变量, 在项目的任何地方都可以访问到, 不需要每一次使用的时候, 都引入. 尝试1:创建 global.js 并且在其中定义   let a = 10 ...

  6. 吴恩达深度学习:2.1Logistic Regression逻辑回归及其损失函数

    1.Logistic Regression是一个二元分类问题 (1)已知输入的特征向量x可能是一张图,你希望把它识别出来,这是不是猫图,你需要一个算法,可以给出预测值,更正式的y是一个概率,当输入特征 ...

  7. 图解Qt安装(Linux平台)

    http://c.biancheng.net/view/3886.html Linux 发行版虽然众多,但 Qt 安装过程大同小异,本节以 CentOS 7 为例来演示 Qt 的安装. 在<Qt ...

  8. PAT Advanced 1006 Sign In and Sign Out (25 分)

    At the beginning of every day, the first person who signs in the computer room will unlock the door, ...

  9. 4--面试总结-promise

    promise异步原理: 定义:promise是异步编程的解决方案,可以解决异步回调地狱的问题: 原理:三种状态两种结果的一个状态机:三种状态(pending,fulfilled,rejected)两 ...

  10. java环境contos上solr-5.5.0 安装部署

    本人qq群也有许多的技术文档,希望可以为你提供一些帮助(非技术的勿加). QQ群:   281442983 (点击链接加入群:http://jq.qq.com/?_wv=1027&k=29Lo ...