473,770 Members | 1,644 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C API : Creating a Py_Method object from a C function.

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
Python interface function stores C++ function pointer
Python interface function generates new Py_Object method pointer
pointing to a different C python function. (This different function
calls the stored C++ function pointer)
Python interface function calls python function
Python function calls the python method pointer it was passed
C python function then calls the stored C++ function pointer.
The problem in this workflow is taking the C python function that I've
defined (using the standard "static PyObject *someFunction(P yObject
*self, PyObject *args)" method) and converting this into a Py_Object.
Any ideas?

Py_Method doesn't seem to allow you to generate a new one with your own
pointers inside... and I can't see anything else in the docs that might
allow me to do this...
Thanks for any advice!

--
Hugh Macdonald

Jul 21 '05 #1
3 1817
Hugh Macdonald wrote:
The problem in this workflow is taking the C python function that I've
defined (using the standard "static PyObject *someFunction(P yObject
*self, PyObject *args)" method) and converting this into a Py_Object.
Any ideas?


You should use PyCFunction_New (Ex), passing a static PyMethodDef
variable that you define along with your function definition.

Regards,
Martin
Jul 21 '05 #2
Thanks Martin - that worked wonderfully....
For the record (and for anyone searching for this in future), here's
the code that worked (with names changed to protect my job...)
myPython is the C++/Python interface class containing static methods
which pass on calls to the underlying python module. It's not really
commented, but if you're trying to do this kind of thing, it should
give you what you need.

----------------------------------------------------------------------------------------------------
// myPython.h

#ifndef ___MYPYTHON_H__ _
#define ___MYPYTHON_H__ _

#include <list>

using namespace std;

typedef struct _object PyObject;
typedef void (*loadCallback) (string message, int progress, void
*callbackData);

static PyObject *myPython_doLoa dCallback(PyObj ect *self,
PyObject *args);

class myPython {
public:
static list<string> *loadDetails(st ring file, loadCallback
callbackFunc = NULL, void *callbackData = NULL);
static void doLoadCallback( string message, int
progress);
private:
static PyObject *getResults(cha r *moduleName, char
*functionName, PyObject *args);

static loadCallback callbackFunc;
static void *callbackData;
};

#endif // ___MYPYTHON_H__ _
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
// myPython.cpp

#include <myPython.h>
#include <Python.h>

loadCallback myPython::callb ackFunc = NULL;
void *myPython::call backData = NULL;

list<string> *myPython::load Details(string file, loadCallback
newCallbackFunc , void *newCallbackDat a)
{
PyObject *pArgs, *pResult;

callbackFunc = newCallbackFunc ;
callbackData = newCallbackData ;

PyMethodDef *callbackFuncti onDef = new PyMethodDef;
callbackFunctio nDef->ml_name = "doLoadCallback ";
callbackFunctio nDef->ml_meth = &myPython_doLoa dCallback;
callbackFunctio nDef->ml_flags = 1;

PyObject *pyCallbackFunc = PyCFunction_New (callbackFuncti onDef,
NULL);

pArgs = Py_BuildValue(" (sO)", file.c_str(), pyCallbackFunc) ;

pResult = getResults("myP ythonModule", "loadDetail s", pArgs);

if(!pResult)
{
Py_DECREF(pArgs );
return NULL;
}

if(PyList_Check (pResult))
{
// Convert pResult into a list<string> and return that.
}

return NULL;
}

PyObject *myPython_doLoa dCallback(PyObj ect *self, PyObject *args)
{
char *message;
int progress;

if(!PyArg_Parse Tuple(args, "si", &message, &progress))
return NULL;

myPython::doLoa dCallback(messa ge, progress);

return Py_None;
}

void myPython::doLoa dCallback(strin g message, int progress)
{
if(callbackFunc )
callbackFunc(me ssage, progress, callbackData);
}
----------------------------------------------------------------------------------------------------

Jul 21 '05 #3
Hugh Macdonald wrote:
PyMethodDef *callbackFuncti onDef = new PyMethodDef;
callbackFunctio nDef->ml_name = "doLoadCallback ";
callbackFunctio nDef->ml_meth = &myPython_doLoa dCallback;
callbackFunctio nDef->ml_flags = 1;


I think this gives a memory leak. I was rather thinking of

static PyMethodDef doLoadCallback = {
"doLoadCallback ", &myPython_doLoa dCallback, 1
};

PyObject *pyCallbackFunc = PyCFunction_New (&doLoadCallbac k,
NULL);

Since you have to write the C(++) functions statically, you can also
provide the PyMethodDef objects statically.

Regards,
Martin
Jul 21 '05 #4

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

Similar topics

1
3406
by: Dixie | last post by:
I wish to add some fields to an existing table in code. I am using the following code from rkc. CurrentDb.Execute ("ALTER TABLE MyTable ADD MyNewField Text 25") This works , but I need to also set the Required, Allow Zero Length and Indexed attributes. I have tried but keep getting a syntax error. Also, can I set the default value of a field in code? Has anyone some examples of these. TIA
6
1768
by: Davinci_Jeremie | last post by:
Hi Newbee here to C# I have a simple questions... In a Hello world example how does the class object Hello exist with out creating it? I come from object pascal where everything object is created then used. In object pascal you can call a method a "class" and it means you can call it by the name of the class and the function name with out creating it like "Hello.Main()" is that true for key word "static"? Also what if I have more...
15
6750
by: Carlos Lozano | last post by:
Hi, What is the right way to create an OCX COM component. The component is already registerred, but can't create an instance. I am using the reference to the interop module created. If I use javascript or vbscript it works. I will appreciate any help. I do the following (C#):
6
1920
by: Simon Verona | last post by:
I would normally use code such as : Dim Customer as new Customer Dim t as new threading.thread(AddressOf Customer.DisplayCustomer) Customer.CustomerId=MyCustomerId t.start Which would create a new thread to display a customer on the screen for example. However, I have a problem with circular references in my objects which means that I have to load the customer object using reflection ie :
22
2778
by: ypjofficial | last post by:
Is there any possibility of invoking the member functions of a class without creating an object (or even a pointer to ) of that class. eg. #include <iostream.h> class test { public: void fun() {
9
1423
by: Brian | last post by:
I have a question that some may consider silly, but it has me a bit stuck and I would appreciate some help in understanding what is going on. For example, lets say that I have a class that creates a student object. Class Student: def setName(self, name) self.name = name
17
46558
Motoma
by: Motoma | last post by:
This article is cross posted from my personal blog. You can find the original article, in all its splendor, at http://motomastyle.com/creating-a-mysql-data-abstraction-layer-in-php/. Introduction: The goal of this tutorial is to design a Data Abstraction Layer (DAL) in PHP, that will allow us to ignore the intricacies of MySQL and focus our attention on our Application Layer and Business Logic. Hopefully, by the end of this guide, you will...
2
3324
by: ChrisO | last post by:
I've been pretty infatuated with JSON for some time now since "discovering" it a while back. (It's been there all along in JavaScript, but it was just never "noticed" or used by most until recently -- or maybe I should just speak for myself.) The fact that JSON is more elegant goes without saying, yet I can't seem to find a way to use JSON the way I *really* want to use it: to create objects that can be instantated into multiple...
3
2284
by: Bartholomew Simpson | last post by:
I am writing some C++ wrappers around some legacy C ones - more specifically, I am providing ctors, dtors and assignment operators for the C structs. I have a ton of existing C code that uses these structs. A typical usage case will be as ff (note the code below is Pseudocode and WILL NOT compile) //example structs (I have left out the ctors/dtors etc for brevity sake) struct MyStructA
0
9432
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
10232
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...
1
10008
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8891
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
7420
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
6682
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
5454
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3974
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
3578
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.