473,763 Members | 1,373 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

PyCFunction_New () ?

Is it possible to create a Python-callable object, dynamically, in C/C++? I
have a GUI app in C++, with the app logic in Python, called from the
GUI via the Python C API. I need be able to call a callback function
in C/C++ from the Python, in response to an event (socket, whatever...)
that the Python is aware of. Callbacks in Python, called from C/C++
are very straightforward , but I haven't been able to find any examples
of the converse.

So I want to be able to do something like:

PyCFunction *myCallback(PyO bject *ob, PyObject *args) { ... }

{
PyObject *somePythonObje ct;
...
PyObject *myCallbackObje ct = PyFunction_New( myCallback, ...);
PyObject_CallMe thod(somePython Object, "setCallbac k", myCallbackObjec t);
...
}

Even better would be:

PyCFunction *MyClass::pyCal lback(PyObject *ob, PyObject *args) { ... }

MyClass::MyClas s()
{
...
PyObject_CallMe thod(somePython Object, "setCallbac k", this->pyCallback);
...
}

Any help greatly appreciated!
Jul 18 '05 #1
3 4808
Scott Deerwester <sc***@deerwest er.org> wrote:
Is it possible to create a Python-callable object, dynamically, in C/C++? I
Sure! But I'm not clear on why you want to create it dynamically. The
C++ code is there all the time, isn't it? So why not the wrapping of it
into Python-callable terms...?
Even better would be:

PyCFunction *MyClass::pyCal lback(PyObject *ob, PyObject *args) { ... }

MyClass::MyClas s()
{
...
PyObject_CallMe thod(somePython Object, "setCallbac k", this->pyCallback);
...
}
Here pyCallback _returns_ a pointer to a PyCFunction, yet you want to
SET it as the callback...? I'm confused! Also, PyObject_CallMe thod
needs a format string as its 3rd arg, before the args 'proper' -- do you
intend to omit it? Why? Again, I'm confused.

Any help greatly appreciated!


You can call PyCFunction_New , passing it a first argument that's a
PyMethodDef struct pointer, and a 2nd argument that's a PyObject*
(whatever you want the C function to receive as the first argument,
self). PyMethodDef is, of course:

struct PyMethodDef {
char *ml_name;
PyCFunction ml_meth;
int ml_flags;
char *ml_doc;
};
typedef struct PyMethodDef PyMethodDef;

What problems is this giving you...?
Alex
Jul 18 '05 #2
Alex Martelli wrote:
Scott Deerwester <sc***@deerwest er.org> wrote:
Is it possible to create a Python-callable object, dynamically, in C/C++?
I
Sure! But I'm not clear on why you want to create it dynamically. The
C++ code is there all the time, isn't it? So why not the wrapping of it
into Python-callable terms...?


Because I'd like to have multiple instances of the class that has (or is
somehow associated with) the C/C++ callback, and to be able to hand a
corresponding Python object a Python-callable callback that ends up
invoking the C++ callback for a particular C++ class instance...

That's a lot of words, but the intention is:

CObj1 = new SomeClass();
/* CObj1 constructor instantiates a Python SomePyClass object PObj1 */
/* CObj1 calls PObj1.setCallba ck(CObj1->someMethod) */
CObj2 = new SomeClass();
/* CObj2 constructor instantiates a Python SomePyClass object PObj2 */
/* CObj2 calls PObj2.setCallba ck(CObj1->someMethod) */

....

# PObj1 decides to call its callback, which calls CObj1->someMethod()

# PObj2 decides to call its callback, which calls CObj2->someMethod()

So the C++ function is (of course) not dynamic, but the Python object
that wraps it is.
You can call PyCFunction_New , passing it a first argument that's a
PyMethodDef struct pointer, and a 2nd argument that's a PyObject*
(whatever you want the C function to receive as the first argument,
self). PyMethodDef is, of course:

struct PyMethodDef {
char *ml_name;
PyCFunction ml_meth;
int ml_flags;
char *ml_doc;
};
typedef struct PyMethodDef PyMethodDef;

What problems is this giving you...?


I was getting confused between a PyCFunction (which isn't a PyObject,
is it?) and PyCFunction_New ... which isn't in the API documentation.

I'll have at it with what you've given me. Thanks!
Jul 18 '05 #3
Scott Deerwester <sc***@p3intern ational.org> wrote:
Alex Martelli wrote:
Scott Deerwester <sc***@deerwest er.org> wrote:
Is it possible to create a Python-callable object, dynamically, in C/C++?
I


Sure! But I'm not clear on why you want to create it dynamically. The
C++ code is there all the time, isn't it? So why not the wrapping of it
into Python-callable terms...?


Because I'd like to have multiple instances of the class that has (or is
somehow associated with) the C/C++ callback, and to be able to hand a
corresponding Python object a Python-callable callback that ends up
invoking the C++ callback for a particular C++ class instance...


Ah, you want to make "bound methods" from C++...? That's a tall order
indeed. In C++ itself, in fact, you couldn't.

Fortunately, you can exploit the 2nd argument of PyCFunction_New . Place
the pointer to the C++ object there, wrapped into a PyObject (or cast
into a PyObject* if you feel frisky...!-). Your C function unwraps it
or casts it back, and then can call the C++ method on the suitable
instance thus recovered.
Alex
Jul 18 '05 #4

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

Similar topics

12
1945
by: Thomas Heller | last post by:
I once knew how to do it, but I cannot find or remember it anymore: How can I attach *class* methods to a type in C code, when I have a function PyObject *func(PyObject *type, PyObject *arg); with the METH_O calling convention? The type is already created, I cannot insert it into the tp_methods array anymore.
0
996
by: Bo Peng | last post by:
Dear list, My SWIG generated module (myModule) needs an array-like object (carray) to work. Carray objects are created both internally (in C++ level) and through Python so I have to load it when myModule initializes. carray is modified from arraymodule.c and is quite simple: static PyMethodDef a_methods = {
0
1195
by: Iker Arizmendi | last post by:
Hello all. Is there a convenient scheme within a C extension to add methods to a type in such a way as to allow me to transparently add a "proxy" around them? For example: typedef PyObject* (*PyMethodCall)(PyObject*, PyObject*); PyObject* middleMan(PyObject* self, PyObject* args) { printf("Before call to wrapped funct\n");
3
1817
by: Hugh Macdonald | last post by:
I've got a pure python module that parses a certain type of file. It has a load() function that allows a callback function to be passed for getting progress information. In straight python, this works fine. However, I'm now trying to use this from a C++ program. The current flow that I'm trying to get is as follows: C++ calls python interface function, passing a C++ function pointer
0
1186
by: SkyRanger | last post by:
Hi! I make class extension from Delphi, but i have problem. Here my code: //==================================================================== {pyClassMethod} function pyClassMethod( self, args : PPyObject ) : PPyObject; cdecl; var Strs : PChar;
2
1203
by: SkyRanger | last post by:
I create class: FOClassName:= PyString_FromString(ClasName); FClass:= PyClass_New(nil, FDict, FOClassName); PyDict_SetItemString(FDict, ClasName, FClass); Py_DECREF(FOClassName); Py_DECREF(FDict); Py_DECREF(FClass); Add methods for it:
3
1703
by: Torsten Bronger | last post by:
Hallöchen! I'd like to script C++ funtions by an embedded Python interpreter. So far, my C++ main() function contains: Py_Initialize(); Py_InitModule("pp3", PythonMethods); PyRun_SimpleString("from pp3 import *"); PyRun_AnyFile(stdin, NULL); Py_Finalize();
2
1352
by: Ben Sizer | last post by:
I have Python embedded in a C++ application (yes, yes, I know, I'd prefer it the other way around too) and essentially need to expose some read-only values and functions to Python so it can be used to script the host application. When scripting a similar app in TCL, it's possible to associate each command with some client data, so that the command can be written in the script as a free function but it actually executes in some sort of...
0
1214
by: Ben Sizer | last post by:
In following the example given at <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/54352>, I find that if I instead try to create PyMethodDef instances on the stack and create methods that way, rather than providing pointers to a static array of them, executing the method later raises an exception from PyCFunction_Call. Is it required that the PyMethodDef persists throughout the execution of the Python program? If so, why isn't...
0
9563
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
9998
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
9822
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...
0
8822
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7366
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...
0
6642
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5270
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3917
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
3
2793
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.