473,796 Members | 2,558 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Function References

Greetings,

I'm trying to wrap a function in a C library as a compiled C Python
module. Everything is going great, but I've hit a snag. There's a
function in the form of this:

First the typedef:
typedef void(*FPtr_Devi ceMessageHandle r) (const DeviceMessage, const
char*);

Then the actual function prototype:
FPtr_DeviceMess ageHandler
RegisterDeviceM essageHandler(F Ptr_DeviceMessa geHandler);

Whenever this USB device I'm using generates a message, it's then sent
to that function whose reference you passed to
RegisterDeviceM essageHandler() . Here's an example:

void testfunc() {
printf("test");
}
....on to main()
RegisterDeviceM essageHandler(& testfunc)

So I've defined a similar function on my C module to do just this,
using the passed function reference to allow the device to send
messages to a Python function of the user's choice. I'm just not sure
how to do this, and the tutorials I've been digging through don't
offer any help. I've found some functions that look promising, but
can't figure out how to cast the function reference from Python into
something the C RegisterDevice. .. function can handle. Here's what
I've got:

static PyObject *
Py1_RegisterDev iceMessageHandl er(PyObject *self, PyObject *args)
{
PyObject *handle, *parsed;

if(!PyArg_Parse Tuple(args, "O", handle)) {
return NULL;
}

parsed = PyMethod_Functi on(handle);
I1_RegisterDevi ceMessageHandle r(PyMethod_Func tion(handle));

Py_RETURN_TRUE;
} // end Py1_RegisterDev iceMessageHandl er()

This fails since PyMethod_Functi on returns a PyObject. Is there a way
to cast this to something generic? Casting to (void*) didn't seem to
work.

Thanks in advance!
Jul 31 '08
14 1323
>Ctypes is a since python2.5 built-in module that allows to declare
>interfaces to C-libraries in pure python. You declare datatypes and
function prototypes, load a DLL/SO and then happily work with it. No C, no
compiler, no refcounts, no nothing.

And you can pass python-functions as callbacks.
sq***********@g mail.com wrote:
The first sentence (and some really crummy licensing restrictions
imposed by the library distributor) alone here excludes this as a
valid option for this particular case, I definitely need Python 2.4
support.
Perhaps all is not lost: ctypes works from Python 2.3 up. That first
sentence is saying that since Python 2.5 it has been included in the
standard Python distribution, but you can still download it separately.

-M-
Jul 31 '08 #11
sq***********@g mail.com wrote:
Greetings,

I'm trying to wrap a function in a C library as a compiled C Python
module. Everything is going great, but I've hit a snag. There's a
function in the form of this:

First the typedef:
typedef void(*FPtr_Devi ceMessageHandle r) (const DeviceMessage, const
char*);

Then the actual function prototype:
FPtr_DeviceMess ageHandler
RegisterDeviceM essageHandler(F Ptr_DeviceMessa geHandler);
[...]
[i] can't figure out how to cast the function reference from Python into
something the C RegisterDevice. .. function can handle.
Mere casting won't do the trick. The function reference from Python is
basically just an object that contains byte-code to be executed by the
Python Virtual Machine. There is no way you can magically transform that
into a C function by casting the Python object pointer to anything.

You'll need a write a C function that will call a given Python function,
and then you need to supply the pointer to that C function as your
DeviceMessageHa ndler callback function, and somehow communicate to your
C function which Python function it should call.

Good luck.

--
Carsten Haese
http://informixdb.sourceforge.net
Jul 31 '08 #12
sq***********@g mail.com schrieb:
On Jul 31, 10:47 am, "Diez B. Roggisch" <de...@nospam.w eb.dewrote:
>I take the freedom to do so as I see fit - this is usenet...

Fine, then keep beating a dead horse by replying to this thread with
things that do nobody any good. It seems like there are a lot better
way to waste time, though.
You mean like trying to wrap ones head around the rather simple Python C
API, not getting a callback mechanism implemented?

For the record: I've wrapped C-libs myself, including callbacks. Been
there, done that, discovered (years later) cytpes, been there for good.
The Python/C API can get me back further without reliance on third-
party libraries than ctypes.
You don't consider your own library a third party lib? And unless you're
wrapping C++, you're opinion is as uninformed as it is wrong.
It also isn't subject to the quirks that
ctypes is on platforms other than Windows (the target application runs
on Windows, Mac, and eventually Linux once the original distributor
has drivers for the device). I'm not even sure ctypes could load the
lib/driver the distributor packaged.
Oh please. I'm 98% working on linux & osx. ctypes does a great job on
these platforms.

Regarding your objections I can only say: whatever the python runtime
can load because of the underlying ld, ctypes can load. simply because
they are the same. If *that* was the actual cause of problems, we
wouldn't even talk about callbacks here.
So really, I appreciate the option in ctypes, it's good stuff. But
it's not for this project.
Stop finding lame excuses for not wanting to ditch the work you've done
in favor of a easier solution. You like your code, you want to keep it,
you want to discover the intricasies of the Python C API? Be my guest.

But stop embarassing yourself inventing reasons like licensing or linker
problems you don't support with any facts whatsoever.
Once again, the original question stands for anyone who has experience
with the Python/C API callbacks.
You know what? Just for the fun of it, I'll take a stab at it.

It's easy: Create a "proxy-function" that matches the prototype of the
c8allback which converts the passed arguments to python values using the
C-api. Then call the registered python function using
PyObject_CallFu nction.

Convert the return-value back to C, and return it.

Make the function get the PyObject* for the call fetch from a global
variable you set in the register-callback function, where you also
register the proxy-function for the first time, or de-register if the
passed value is None or such.

Have fun.
Diez
Jul 31 '08 #13
Lie
On Aug 1, 6:35*am, "Diez B. Roggisch" <de...@nospam.w eb.dewrote:
squishywaf...@g mail.com schrieb:
On Jul 31, 10:47 am, "Diez B. Roggisch" <de...@nospam.w eb.dewrote:
I take the freedom to do so as I see fit - this is usenet...
Fine, then keep beating a dead horse by replying to this thread with
things that do nobody any good. It seems like there are a lot better
way to waste time, though.

You mean like trying to wrap ones head around the rather simple Python C
API, not getting a callback mechanism implemented?

For the record: I've wrapped C-libs myself, including callbacks. Been
there, done that, discovered (years later) cytpes, been there for good.
The Python/C API can get me back further without reliance on third-
party libraries than ctypes.

You don't consider your own library a third party lib? And unless you're
wrapping C++, you're opinion is as uninformed as it is wrong.
It also isn't subject to the quirks that
ctypes is on platforms other than Windows (the target application runs
on Windows, Mac, and eventually Linux once the original distributor
has drivers for the device). I'm not even sure ctypes could load the
lib/driver the distributor packaged.

Oh please. I'm 98% working on linux & osx. ctypes does a great job on
these platforms.

Regarding your objections I can only say: whatever the python runtime
can load because of the underlying ld, ctypes can load. simply because
they are the same. If *that* was the actual cause of problems, we
wouldn't even talk about callbacks here.
So really, I appreciate the option in ctypes, it's good stuff. But
it's not for this project.

Stop finding lame excuses for not wanting to ditch the work you've done
in favor of a easier solution. You like your code, you want to keep it,
you want to discover the intricasies of the Python C API? Be my guest.

But stop embarassing yourself inventing reasons like licensing or linker
problems you don't support with any facts whatsoever.
Once again, the original question stands for anyone who has experience
with the Python/C API callbacks.

You know what? Just for the fun of it, I'll take a stab at it.

* It's easy: Create a "proxy-function" that matches the prototype of the
c8allback which converts the passed arguments to python values using the
C-api. Then call the registered python function using
PyObject_CallFu nction.

Convert the return-value back to C, and return it.

Make the function get the PyObject* for the call fetch from a global
variable you set in the register-callback function, where you also
register the proxy-function for the first time, or de-register if the
passed value is None or such.

Have fun.

Diez
Zen's lesson for today:
THOU SHALT NOT MESS WITH ANY PYTHON'S SEMI-GODS, DEMI-GODS, AND
PYTHON'S GOD.

You're lucky Diez still want to help you with your attitude like that.
May I remind you that we here helps you for free in our free time, be
rude, especially to a frequent member, and you'll get what you deserve.
Aug 28 '08 #14
Zen's lesson for today:
THOU SHALT NOT MESS WITH ANY PYTHON'S SEMI-GODS, DEMI-GODS, AND
PYTHON'S GOD.

You're lucky Diez still want to help you with your attitude like that.
May I remind you that we here helps you for free in our free time, be
rude, especially to a frequent member, and you'll get what you deserve.
Thanks Lie, but I certainly don't consider myself being part of Python's
olymp... :) Others here of course are, and a friendly and open attitude
from everybody sure helps keeping this institution helpful.

This goes also for frequent members - and I do include myself here, as I
*sometimes* forget that myself, but try hard not to.

Diez
Aug 28 '08 #15

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
14954
by: domeceo | last post by:
can anyone tell me why I cannot pass values in a setTimeout function whenever I use this function it says "menu is undefined" after th alert. function imgOff(menu, num) { if (document.images) { document.images.src = eval("mt" +menu+ ".src") } alert("imgOff_hidemenu"); hideMenu=setTimeout('Hide(menu,num)',500);
3
1356
by: RobG | last post by:
I am playing with a script that will allow columns of a table to be moved by dragging them left or right. To do this with functions is fairly straight forward, however after looking at Richard Cornford's version of Table Highlighter I decided to do it using an object. Richard's basic code structure is: var SomeObject = (function() { function someFn01(){
18
9048
by: Steve | last post by:
Hi I have a really weird problem and any assistance would be welcome. I have developed an app in Access 2002. The app runs perfectly on the development machine. I have packaged the app using the Microsoft XP Developer Packaging Wizard (Service Pack 1). The 1st 3 releases of the app ran perfectly on site.
19
2519
by: Deniz Bahar | last post by:
Hi, I would like to call one of my functions the exact name as an existing C library function (for example K&R2 exercises asks me to make an atof function). If I don't include the header with the declaration for the C library function (stdlib.h in this case) then define/declare my own function with the same name, am I safe? It seems to work on my compiler, but I wonder if this is portable or even acceptable? thx
28
4340
by: Larax | last post by:
Best explanation of my question will be an example, look below at this simple function: function SetEventHandler(element) { // some operations on element element.onclick = function(event) {
0
9680
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9528
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10456
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10230
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10012
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7548
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
4118
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3731
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2926
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.