473,322 Members | 1,510 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

C++ extension problem

Hi,

I'm having a bit of trouble when writing a python extension. I can't
seem to figure out what I did wrong.
I tried to make a minimal example, but it's still quite a bit of
code.
It would be very appreciated if anyone could tell me what I've done
wrong.

First a short description of what I've done. The extension just wraps
a string and the class in it will just hold the string data. A 'get'
method is suppsed to just return the string value.
There's a python part that will call C/C++ functions in the
extension.
I've tried using the same approach SWIG has, so the class in the
extension doesn't really have any methods,
it's all done in methods in the module.

This is what it looks like when I try it out (also tried with
different python version and compiler):
% python
Python 2.4.3 (#1, Aug 1 2006, 16:54:29)
[GCC 3.4.6] on sunos5
Type "help", "copyright", "credits" or "license" for more information.
>>from example import StringWrapper
s = StringWrapper("S")
s.get()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "example.py", line 7, in get
def get(self): return _example.get(self._s)
TypeError: argument 1 must be SillyString, not SillyString

Now this is what confuses me: Why does it say that I have the wrong
type when it's the same type as it suggests?

setup.py file:
###########
from distutils.core import setup, Extension
module1 = Extension('_example',
sources = ['_example.cc'])
setup (name = 'example',
ext_modules = [module1])

example.py file:
############
#!/usr/bin/env python
import _example

class StringWrapper(object):
def __init__(self, value):
self._s = _example.new_string(value)
def get(self): return _example.get(self._s)
and finally, the c/c++ file '_example.cc':
(I need to use c++ compiler which means I couldn't use
'staticforward'
and the 'cstring is used instead of 'string.h' )
########################
#include "Python.h"
#include <cstring>

// forward declaration
extern PyTypeObject SillyStringType;

typedef struct {
PyObject_HEAD
char s[21];
} SillyStringObject;

PyObject *
new_string(PyTypeObject *type, PyObject *args)
{
char *value = 0;

if (!PyArg_ParseTuple(args, "s", &value))
return NULL;
SillyStringObject *self = PyObject_NEW(SillyStringObject,
&SillyStringType);
if (self != NULL) {
strncpy(self->s, value, 20);
}
return (PyObject *)self;
}

PyObject *
get(PyTypeObject *type, PyObject *args)
{
SillyStringObject *o;

if (!PyArg_ParseTuple(args, "O!", SillyStringType, &o))
return NULL;
return (PyObject *)PyString_FromString(o->s);
}

PyMethodDef SillyStringMethods[] = {
{"get", (PyCFunction)get, METH_VARARGS,
""
},
{"new_string", (PyCFunction)new_string, METH_VARARGS,
""
},
{NULL, NULL, 0, NULL} /* Sentinel */
};

PyTypeObject SillyStringType = {
PyObject_HEAD_INIT(NULL)
0, /* ob_size */
(char *)"SillyString", /* tp_name */
sizeof(SillyStringObject), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)0, /* tp_dealloc */
(printfunc)0, /* tp_print */
(getattrfunc)0, /* tp_getattr */
(setattrfunc)0, /* tp_setattr */
(cmpfunc)0, /* tp_compare */
(reprfunc)0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
(hashfunc)0, /* tp_hash */
(ternaryfunc)0, /* tp_call */
(reprfunc)0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
"SillyString class." /* tp_doc */
};

extern "C"
{
PyMODINIT_FUNC
init_example(void)
{
PyObject* m;
SillyStringType.tp_new = PyType_GenericNew;
if (PyType_Ready(&SillyStringType) < 0)
return;
m = Py_InitModule3("_example", SillyStringMethods,
"_example module.");
Py_INCREF(&SillyStringType);
PyModule_AddObject(m, "SillyStringObject", (PyObject
*)&SillyStringType);
}
}

Apr 16 '07 #1
5 1320
py***********@gmail.com wrote:
I'm having a bit of trouble when writing a python extension. I can't
seem to figure out what I did wrong.
I tried to make a minimal example, but it's still quite a bit of
code.
It would be very appreciated if anyone could tell me what I've done
wrong.
I can't answer your question since I have no experience writing
extension types. I know this is at least partially a learning exercise
for you, but might I suggest that your time might be better spent
learning Boost.Python instead? It is "a C++ library which enables
seamless interoperability between C++ and the Python programming language."

http://www.boost.org/libs/python/doc/
--
Michael Hoffman
Apr 16 '07 #2
Now this is what confuses me: Why does it say that I have the wrong
type when it's the same type as it suggests?
When referring to the type, you must *always* form the address of the
type structure, including, but not limited to, the line
if (!PyArg_ParseTuple(args, "O!", SillyStringType, &o))
HTH,
Martin
Apr 16 '07 #3
On Apr 16, 9:31 pm, Michael Hoffman <cam.ac...@mh391.invalidwrote:
I can't answer your question since I have no experience writingextensiontypes. I know this is at least partially a learning exercise
for you, but might I suggest that your time might be better spent
learning Boost.Python instead? It is "aC++library which enables
seamless interoperability betweenC++and the Python programming language."

http://www.boost.org/libs/python/doc/
--
Michael Hoffman
Yes, that's good advice. Unfortunately, boost has not been working
very well with the tools I'm forced to use (Sun studio). Otherwise I
would have started there.

/Matt

Apr 17 '07 #4
On Apr 16, 11:44 pm, "Martin v. Löwis" <mar...@v.loewis.dewrote:
Now this is what confuses me: Why does it say that I have the wrong
type when it's the same type as it suggests?

When referring to the type, you must *always* form the address of the
type structure, including, but not limited to, the line
if (!PyArg_ParseTuple(args, "O!", SillyStringType, &o))

HTH,
Martin

Yes, that did help. Thanks.
I assumed that the compiler would warn me about that kind of problem,
but I know better know. :)
Still, the error message is somewhat confusing.

Apr 17 '07 #5
I assumed that the compiler would warn me about that kind of problem,
but I know better know. :)
It's a variable argument list (...). The compiler is not supposed to
give any warnings for that (although I do have a gcc patch that enables
warnings for PyArg_ParseTuple).
Still, the error message is somewhat confusing.
Passing incorrect parameters to variable argument lists causes undefined
behavior. Anything can happen under undefined behavior, including
mysterious error messages, erasure of your hard disk, and reversal of
the global warming.

To understand why the specific error message is printed, you would have
to debug what values are passed on the stack at what point.

Regards,
Martin
Apr 17 '07 #6

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

Similar topics

6
by: Gyger | last post by:
Hello, Three weeks ago, I have started to develop a binding extension for Qt and PHP 5. Now, I can display a dialog box containing some widgets like label, buttons and edit line. I have just...
3
by: Peter Sparago | last post by:
(Sorry in advance for the long post.) Hi, I'm having a great deal of difficulty buiding a Python COM extension. I am using the MSHTML ActiveX control in my application but I need to interact...
3
by: man-in-nature | last post by:
Hello, I have already read several existing posts about xsd:extension, but do not find something useful to my test case. I have one xml file and one xsd file. I can use a simple command line...
5
by: Jeffry van de Vuurst | last post by:
Hi, I'm working on an xml schema and I'm running into some problems relating substitutionGroups and extensions. This xsd validates fine: There are three elements and three complex types and...
7
by: Adam | last post by:
Im trying to add an httphandler for all *.sgf file extensions. I have developed the handler, 1. installed it into the gac 2. added it to the machine.config: <httpHandlers> <add verb="*"...
4
by: pepcag | last post by:
I used http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconalteringsoapmessageusingsoapextensions.asp as a template to create a very simple web method with soap...
1
by: J.P. | last post by:
I've developed a com extension for explorer and another dll linked to the com extension which provides the actual functionality. The extension does nothing more than create an object and pass...
5
by: Chuck Anderson | last post by:
I run Apache 2.0.55, and Php (both 4.4.1 and 5.2.5) on my home PC (Windows XP). One of the scripts that I run daily needs to access a secure URL (https://..............). When I am running Php4,...
6
by: tommybiegs | last post by:
I'm having a weird problem. I can't seem to force php to load an extension using php.ini, but it loads perfectly if I use dl() at the beginning of a test script. In php.ini I've got: ...
8
by: Ron | last post by:
I am building a dynamic image loading class. I have a list of properties that have associated images in a specified directory. The problem they are multiple formats which are not known at...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.