GTK+ Forums Forum Index GTK+ Forums
Discussion forum for GTK+ and Programming. Ask questions, troubleshoot problems, view and post example code, or express your opinions.
 
 FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

How to use Python with C.

 
Post new topic   Reply to topic    GTK+ Forums Forum Index -> GTK+ Example Code
Author Message
caracal
GTK+ Guru


Joined: 21 Jun 2007
Posts: 207
Location: Wilkes Barre Pa

PostPosted: Tue Apr 21, 2009 5:15 pm    Post subject: How to use Python with C. Reply with quote

note: This is just a start i will be adding more soon.

How to call a C Function from Python

test.c
Code: (C)
1
2
3
4
5
6

int add (int a, int b)
{
    return(a+b);
}


gcc -fPIC -c test.c
gcc -shared test.o -o libtest.so

echo $HOME
mkdir $HOME/example

cp libtest.so $HOME/example
export LD_LIBRARY_PATH=$HOME/example

Code: (Python)
1
2
3
4
5
6
7

#!/usr/bin/python

from ctypes import *
libc = CDLL('libtest.so')
print(libc.sum(1, 10))

Reference
[HTML] http://docs.python.org/library/ctypes.html



How to embed Python in C

demo.c
Code: (C)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

#include <Python.h>
/* gcc -Wall -g -o demo demo.c  -I/usr/include/python2.6 -L/usr/lib/python2.6/config -lpython2.6 -lnsl -ldl -lreadline -ltermcap -lieee -lpthread -lutil -lm -Xlinker -export-dynamic */

int main(int argc, char *argv[])
{
  Py_Initialize();
  PyRun_SimpleString("from time import time,ctime\n"
                     "print 'Today is',ctime(time())\n"
                     "print 'Wow we are actually in python right now!'\n"
);
  Py_Finalize();
  printf("Ok we are now back in C.\n");
  return 0;
}


Reference
[HTML] http://docs.python.org/extending/embedding.html#very-high-level-embedding
Back to top
Display posts from previous:   
Post new topic   Reply to topic    GTK+ Forums Forum Index -> GTK+ Example Code All times are GMT
Page 1 of 1

 


Powered by phpBB © 2001, 2005 phpBB Group
CodeBB 1.0 Beta 2
Protected by Anti-Spam ACP