I am a Python veteran, but did not type much in C. In the afternoon, when I did not find anything on the Internet that worked for me, I thought I would ask here and get the help that I need.
What I want to do is write a simple C function that takes a string and returns another string. I plan to link this function in several languages (Java, Obj-C, Python, etc.), so I think it should be pure C?
Here is what I still have. Notice that I get segfault when I try to get 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
I read that segfault is caused by C freeing up the memory that was originally allocated for the returned string. Maybe I'm just barking the wrong tree?
What is the right way to accomplish what I want?
c python ctypes
Thane brimhall
source share