Hi frenz,
Many of the programs are written in C/C++ language. I want to call a function in C/C++ from python program.
Can anybody tell me how to do it?

Recommended Answers

All 3 Replies

Write your C functions and compile to a DLL, then access similar to this example ...

# using the module ctypes you can access DLLs written in C/C++
# ctypes converts between Python types and C types
# there are two ways to write DLLs:
# most common uses cdecl, import with cdll
# Win and VB may use stdcall, import with windll
# note: module ctypes is builtin in Python25

from ctypes import *

# as an example let's use msvcrt.dll
# this is the MS C library containing many standard C functions
# import the C function strchr() from msvcrt.dll
strchr = cdll.msvcrt.strchr

# declare the return type ...
# a pointer to a string (which then converts to a Python string)
strchr.restype = c_char_p

# these are the argument types ...
# Python string converts to pointer to a string --> c_char_p
# Python single char string converts to C char --> c_char
strchr.argtypes = [c_char_p, c_char]

# now call the function and show the result
print strchr('abcdefg', 'd')  # result --> defg

I got an error when i executing the line 13. I am using Ubuntu Linux distribution. Can u plz help me?

Read lines 10 and 11, I think that particular DLL is a creation of Microsoft and is only available on Windows.

I don't have a Linux machine, but there should be a counterpart there. I am tempted to download Ubuntu to test out the CD version.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.