Re: How to pass String BYREF to C function?
Andrew Wilson <[email protected]>
| Newsgroups | gmane.comp.python.ctypes |
|---|---|
| Message-ID | <[email protected]> |
Marco,
You are correct exitResult is a pointer to c_char_p. I don't know
the exact different between ctypes.byref and ctypes.POINTER but the
documentation states that we should use byref as it is much faster...
ctypes.byref(obj[, offset])¶
Returns a light-weight pointer to obj, which must be an instance
of a ctypes type. offset defaults to zero, and must be an integer that
will be added to the internal pointer value.
byref(obj, offset) corresponds to this C code:
(((char *)&obj) + offset)
The returned object can only be used as a foreign function call
parameter. It behaves similar to pointer(obj), but the construction is
a lot faster.
New in version 2.6: The offset optional argument was added.
ctypes.POINTER(type)¶
This factory function creates and returns a new ctypes pointer
type. Pointer types are cached an reused internally, so calling this
function repeatedly is cheap. type must be a ctypes type.
ctypes.pointer(obj)¶
This function creates a new pointer instance, pointing to obj. The
returned object is of the type POINTER(type(obj)).
Note: If you just want to pass a pointer to an object to a foreign
function call, you should use byref(obj) which is much faster.
The code below should do the trick, I must not have had enough coffee
this morning, time for another cup...
import ctypes
import os
if __name__ == "__main__":
if os.name=='nt':
userExit = ctypes.cdll.LoadLibrary("libUserExits.dll")
executeUserExit = userExit.executeUserExit
executeUserExit.argtypes = [ctypes.c_char_p,
ctypes.POINTER(ctypes.c_char_p)]
executeUserExit.restype = ctypes.c_int
exitResult = ctypes.c_char_p()
result = executeUserExit("hello world", ctypes.byref(exitResult))
print exitResult.value
print "Finished"
On Wed, Aug 18, 2010 at 9:22 AM, marco cassisa <[email protected]> wrote:
>
>
> 2010/8/18 Andrew Wilson <[email protected]>
>>
>> Hey Lynton,
>> I guess the casting and create_stream_buffer was for not as pointed out by TP, the following seems to work fine.I'm really a hack at ctypes...
>>
>>
>> stream = ctypes.c_char_p("hello world")
>> exitResult = ctypes.c_char_p()
>>
>>
>> result = executeUserExit(stream, ctypes.byref(exitResult))
>>
> IMHO exitResult - I insist - must be a pointer to c_char_p() ( and in fact the signature is
>
> int executeUserExit(char *buffer, char **userExitResultBuffer){
>
> ) and correctly Lynton Grice declared the arguments' types
>
> executeUserExit.argtypes = [c.c_char_p, c.POINTER(c.c_char_p)]
>
> in his working code
>
> I can be wrong of course, i am a newbie!
>
> marco
------------------------------------------------------------------------------
This SF.net email is sponsored by
Make an app they can't live without
Enter the BlackBerry Developer Challenge
http://p.sf.net/sfu/RIM-dev2dev