ctypes从c函数返回一个字符串 [英] ctypes return a string from c function

查看:468
本文介绍了ctypes从c函数返回一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的资深人士,但对C的涉猎却不多。半天没在网上找到对我有用的任何东西之后,我想我会在这里问问题并获得所需的帮助。



我想做的是编写一个简单的C函数,该函数接受一个字符串并返回另一个字符串。我打算用几种语言(Java,Obj-C,Python等)绑定此函数,所以我认为它必须是纯C语言?



这就是我所拥有的至今。注意,尝试在Python中检索值时遇到段错误。



hello.c



  #include< stdlib.h> 
#include< stdio.h>
#include< string.h>

const char * hello(char * name){
static char greeting [100] = Hello,;
strcat(问候,名字);
strcat(问候,!\n);
printf(%s\n,问候);
返回问候语;
}



main.py



 导入ctypes 
hello = ctypes.cdll.LoadLibrary('./ hello.so')
name = Frank
c_name = ctypes。 c_char_p(name)
foo = hello.hello(c_name)
print c_name.value#可以正常返回
print ctypes.c_char_p(foo).value#segfault

我读到段错误是由C释放最初为返回的字符串分配的内存引起的。也许我只是在吠错一棵树?



完成我想要的东西的正确方法是什么?

解决方案

在hello.c中,您将返回一个本地数组。您必须返回一个指向数组的指针,该数组必须使用malloc动态分配。

  char * hello(char *名称)
{
char hello [] = Hello;
char excla [] =!\n;
char * greeting = malloc(sizeof(char)*(strlen(name)+ strlen(hello)+ strlen(excla)+ 1));
if(greeting == NULL)exit(1);
strcpy(问候,你好);
strcat(打招呼,名字);
strcat(打招呼,不打扰);
返回问候语;
}


I'm a Python veteran, but haven't dabbled much in C. After half a day of not finding anything on the internet that works for me, I thought I would ask here and get the help I need.

What I want to do is write a simple C function that accepts a string and returns a different string. I plan to bind this function in several languages (Java, Obj-C, Python, etc.) so I think it has to be pure C?

Here's what I have so far. Notice I get a segfault when trying to retrieve the value in Python.

hello.c

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

const char* hello(char* name) {
    static char greeting[100] = "Hello, ";
    strcat(greeting, name);
    strcat(greeting, "!\n");
    printf("%s\n", greeting);
    return greeting;
}

main.py

import ctypes
hello = ctypes.cdll.LoadLibrary('./hello.so')
name = "Frank"
c_name = ctypes.c_char_p(name)
foo = hello.hello(c_name)
print c_name.value # this comes back fine
print ctypes.c_char_p(foo).value # segfault

I've read that the segfault is caused by C releasing the memory that was initially allocated for the returned string. Maybe I'm just barking up the wrong tree?

What's the proper way to accomplish what I want?

解决方案

In hello.c you return a local array. You have to return a pointer to an array, which has to be dynamically allocated using malloc.

char* hello(char* name)
{ 
    char hello[] = "Hello ";
    char excla[] = "!\n";
    char *greeting = malloc ( sizeof(char) * ( strlen(name) + strlen(hello) + strlen(excla) + 1 ) );
    if( greeting == NULL) exit(1);
    strcpy( greeting , hello);
    strcat(greeting, name);
    strcat(greeting, excla);
    return greeting;
}

这篇关于ctypes从c函数返回一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆