Search Results

Search found 73 results on 3 pages for 'ctypes'.

Page 1/3 | 1 2 3  | Next Page >

  • Odd difference between Python 2.5 and Python 2.6 on MacOS 10.6 using ctypes and libproc proc_pidinfo

    - by cemasoniv
    I'm trying to determine the current working directory of a process given its PID. The command-line utility lsof does something similar. Here's the source to the python script: import ctypes from ctypes import util import sys PROC_PIDVNODEPATHINFO = 9 proc = ctypes.cdll.LoadLibrary(util.find_library("libproc")) print(proc.proc_pidinfo) class vnode_info(ctypes.Structure): _fields_ = [('data', ctypes.c_ubyte * 152)] class vnode_info_path(ctypes.Structure): _fields_ = [('vip_vi', vnode_info), ('vip_path', ctypes.c_char * 1024)] class proc_vnodepathinfo(ctypes.Structure): _fields_ = [('pvi_cdir', vnode_info_path), ('pvi_rdir', vnode_info_path)] inst = proc_vnodepathinfo() pid = int(sys.argv[1]) ret = proc.proc_pidinfo( pid, PROC_PIDVNODEPATHINFO, 0, ctypes.byref(inst), ctypes.sizeof(inst) ) print(ret, inst.pvi_cdir.vip_path) However, even though this script behaves as expected on Python 2.6, it does not work in Python 2.5: host:dir user$ sudo /usr/bin/python2.6 script.py 2698 <_FuncPtr object at 0x100419ae0> (2352, '/') host:dir user$ sudo /usr/bin/python2.5 script.py 2698 <_FuncPtr object at 0x19fdc0> (0, '') (PID 2698 is "Activity Monitor.app"). Note the different return values. Since this program strongly based on ctypes, I can't imagine any difference in Python itself that would cause this. The same behavior (as Python 2.5) occurs with my self-built Python 3.2. I'm not sure what versioning information I can give to help track down the weirdness -- or even come up with a solution for 2.5 -- but here's some stuff: host:dir user$ otool -L /usr/bin/python2.6 /usr/bin/python2.6: /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.0) host:dir user$ otool -L /usr/bin/python2.5 /usr/bin/python2.5 (architecture i386): /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.0) /usr/bin/python2.5 (architecture ppc7400): /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.0) host:dir user$ uname -a Darwin host.local 10.8.0 Darwin Kernel Version 10.8.0: Tue Jun 7 16:33:36 PDT 2011; root:xnu-1504.15.3~1/RELEASE_I386 i386 Thanks to anyone that has a clue about what's going on here:)

    Read the article

  • Does Ctypes Structures and POINTERS automatically free the memory when the Python object is deleted?

    - by jsbueno
    When using Python CTypes there are the Structures, that allow you to clone c-structures on the Python side, and the POINTERS objects that create a sofisticated Python Object from a memory address value and can be used to pass objects by reference back and forth C code. What I could not find on the documentation or elsewhere is what happens when a Python object containing a Structure class that was de-referenced from a returning pointer from C Code (that is - the C function alocated memory for the structure) is itself deleted. Is the memory for the original C structure freed? If not how to do it? Furthermore -- what if the Structure contains Pointers itself, to other data that was also allocated by the C function? Does the deletion of the Structure object frees the Pointers onits members? (I doubt so) Else - -how to do it? Trying to call the system "free" from Python for the Pointers in the Structure is crashing Python for me. In other words, I have this structure filled up by a c Function call: class PIX(ctypes.Structure): """Comments not generated """ _fields_ = [ ("w", ctypes.c_uint32), ("h", ctypes.c_uint32), ("d", ctypes.c_uint32), ("wpl", ctypes.c_uint32), ("refcount", ctypes.c_uint32), ("xres", ctypes.c_uint32), ("yres", ctypes.c_uint32), ("informat", ctypes.c_int32), ("text", ctypes.POINTER(ctypes.c_char)), ("colormap", ctypes.POINTER(PIXCOLORMAP)), ("data", ctypes.POINTER(ctypes.c_uint32)) ] And I want to free the memory it is using up from Python code.

    Read the article

  • Creating a structure from bytes with ctypes and IronPython

    - by Adal
    I have the following CPython code which I now try to run in IronPython: import ctypes class BarHeader(ctypes.Structure): _fields_ = [ ("id", ctypes.c_char * 4), ("version", ctypes.c_uint32)] bar_file = open("data.bar", "rb") header_raw = bar_file.read(ctypes.sizeof(BarHeader)) header = BarHeader.from_buffer_copy(header_raw) The last line raises this exception: TypeError: expected array, got str I tried BarHeader.from_buffer_copy(bytes(header_raw)) instead of the above, but then the exception message changes to TypeError: expected array, got bytes. Any idea what I'm doing wrong?

    Read the article

  • instantiate python object within a c function called via ctypes

    - by gwk
    My embedded Python 3.3 program segfaults when I instantiate python objects from a c function called by ctypes. After setting up the interpreter, I can successfully instantiate a python Int (as well as a custom c extension type) from c main: #import <Python/Python.h> #define LOGPY(x) \ { fprintf(stderr, "%s: ", #x); PyObject_Print((PyObject*)(x), stderr, 0); fputc('\n', stderr); } // c function to be called from python script via ctypes. void instantiate() { PyObject* instance = PyObject_CallObject((PyObject*)&PyLong_Type, NULL); LOGPY(instance); } int main(int argc, char* argv[]) { Py_Initialize(); instantiate(); // works fine // run a script that calls instantiate() via ctypes. FILE* scriptFile = fopen("emb.py", "r"); if (!scriptFile) { fprintf(stderr, "ERROR: cannot open script file\n"); return 1; } PyRun_SimpleFileEx(scriptFile, scriptPath, 1); // close on completion return 0; } I then run a python script using PyRun_SimpleFileEx. It appears to run just fine, but when it calls instantiate() via ctypes, the program segfaults inside PyObject_CallObject: import ctypes as ct dy = ct.CDLL('./emb') dy.instantiate() # segfaults lldb output: instance: 0 Process 52068 stopped * thread #1: tid = 0x1c03, 0x000000010000d3f5 Python`PyObject_Call + 69, stop reason = EXC_BAD_ACCESS (code=1, address=0x18) frame #0: 0x000000010000d3f5 Python`PyObject_Call + 69 Python`PyObject_Call + 69: -> 0x10000d3f5: movl 24(%rax), %edx 0x10000d3f8: incl %edx 0x10000d3fa: movl %edx, 24(%rax) 0x10000d3fd: leaq 2069148(%rip), %rax ; _Py_CheckRecursionLimit (lldb) bt * thread #1: tid = 0x1c03, 0x000000010000d3f5 Python`PyObject_Call + 69, stop reason = EXC_BAD_ACCESS (code=1, address=0x18) frame #0: 0x000000010000d3f5 Python`PyObject_Call + 69 frame #1: 0x00000001000d5197 Python`PyEval_CallObjectWithKeywords + 87 frame #2: 0x0000000201100d8e emb`instantiate + 30 at emb.c:9 Why does the call to instantiate() fail from ctypes only? The function only crashes when it calls into the python lib, so perhaps some interpreter state is getting munged by the ctypes FFI call?

    Read the article

  • Python ctypes argument errors

    - by Patrick Moriarty
    Hello. I wrote a test dll in C++ to make sure things work before I start using a more important dll that I need. Basically it takes two doubles and adds them, then returns the result. I've been playing around and with other test functions I've gotten returns to work, I just can't pass an argument due to errors. My code is: import ctypes import string nDLL = ctypes.WinDLL('test.dll') func = nDLL['haloshg_add'] func.restype = ctypes.c_double func.argtypes = (ctypes.c_double,ctypes.c_double) print(func(5.0,5.0)) It returns the error for the line that called "func": ValueError: Procedure probably called with too many arguments (8 bytes in excess) What am I doing wrong? Thanks.

    Read the article

  • ctypes DLL with optional dependencies

    - by pisswillis
    Disclaimer: I'm new to windows programming so some of my assumptions may be wrong. Please correct me if so. I am developing a python wrapper for a C API using ctypes. The API ships with both 64 and 32 DLLs/LIBs. I can succesfully load the DLL using ctypes.WinDLL('TheLibName') and call functions etc etc. However some functions were not doing what they should. Upon further investigation it appears that the 32bit DLL is being used, which is what is causing the unexpected behaviour. I have tried using ctypes.WinDLL('TheLibName64') but the module is not found. I have tried registering the DLL with regsrv32, but it reports there is no entry point (it also reports no entry point when I try and register TheLibName, which is found by WinDLL(). The DLL came with a sample project in Visual Studio (I have 0 experience with VS so again please correct me here) which builds both 32 and 64 bit versions of the sample project. In the .vcsproj file the configurations for the 64 bit version include: AdditionalDependencies="TheLibName64.lib" in the VCLinkerTool section. In windows/system32 there are both TheLibName.dll/.lib, and TheLibName64.dll/.lib. So it seems to me that my problem is now to make the python ctypes DLL loader load these optional dependencies when the DLL is loaded. However I can't find any information on this (perhaps because, as a doze noob, I do not know the correct terminology) in the ctypes documentation. Is there a way to do this in ctypes? Am I going about this in completely the wrong way? Any help or general information about optional DLL dependencies and how they are loaded in windows would be much appreciated. Thanks

    Read the article

  • ctypes for static libraries?

    - by Begbie00
    Hi all - I'm attempting to write a Python wrapper for poker-eval, a c static library. All the documentation I can find on ctypes indicates that it works on shared/dynamic libraries. Is there a ctypes for static libraries? I know about cython, but should I use that or recompile the poker-eval into a dynamic library so that I can use ctypes? Thanks, Mike

    Read the article

  • ctypes import not working on python 2.5

    - by user551906
    Hi, I am trying to import ctypes, and I am using Python 2.5.5 installed using macports (on Mac OS X 10.6). I get an error saying "ImportError: No module named _ctypes" (see details below). As I understand it ctypes is supposed to come preinstalled for python 2.5. Any suggestions? thanks, Saurabh Error details: $ python Python 2.5.5 (r255:77872, Nov 30 2010, 00:05:47) [GCC 4.2.1 (Apple Inc. build 5659)] on darwin Type "help", "copyright", "credits" or "license" for more information. import ctypes Traceback (most recent call last): File "", line 1, in File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ctypes/init.py", line 10, in from _ctypes import Union, Structure, Array ImportError: No module named _ctypes

    Read the article

  • Access array of c-structs using Python ctypes

    - by sadris
    I have a C-function that allocates memory at the address passed to and is accessed via Python. The pointer contents does contain an array of structs in the C code, but I am unable to get ctypes to access the array properly beyond the 0th element. How can I get the proper memory offset to be able to access the non-zero elements? Python's ctypes.memset is complaining about TypeErrors if I try to use their ctypes.memset function. typedef struct td_Group { unsigned int group_id; char groupname[256]; char date_created[32]; char date_modified[32]; unsigned int user_modified; unsigned int user_created; } Group; int getGroups(LIBmanager * handler, Group ** unallocatedPointer); ############# python code below: class Group(Structure): _fields_ = [("group_id", c_uint), ("groupname", c_char*256), ("date_created", c_char*32), ("date_modified", c_char*32), ("user_modified", c_uint), ("user_created", c_uint)] myGroups = c_void_p() count = libnativetest.getGroups( nativePointer, byref(myGroups) ) casted = cast( myGroups, POINTER(Group*count) ) for x in range(0,count): theGroup = cast( casted[x], POINTER(Group) ) # this only works for the first entry in the array: print "~~~~~~~~~~" + theGroup.contents.groupname Related: Access c_char_p_Array_256 in Python using ctypes

    Read the article

  • ctypes and PySide

    - by Timothy Baldridge
    I'm building an app with PySide, there's some image manipulation that needs to be done and using Python code for this is way too slow. Therefore I hacked out a .dll file that will do it for me. The function definition is as follows: extern "C" { QRectF get_image_slant(QImage *img, float slantangle, float offset) { Now I can load this function in via ctypes. But I can't seem to get ctypes to accept a QImage. I tried calling it like this: ext.get_image_slant(QImage(), 0, 0) And the reply I get is: File "<stdin>", line 1, in <module> ctypes.ArgumentError: argument 1: <type 'exceptions.TypeError'>: Don't know how to convert parameter 1 I tired casting the QImage to a c_void_p and it doesn't like that either. From what I can tell QImage() in python should map exactly to a QImage * in C, but Python doesn't seem to understand that.. Is there any way to force the casting?

    Read the article

  • OpenCV, Python (ctypes), and OS X 10.5: dylib errors/confusion

    - by Jeff
    I have tried two brands of ctypes (ctypes-opencv and another) wrappers for OpenCV (2.0 from svn head), can use Python and OpenCV in the Python console, but whenever I try to import the packages (from ctypes_opencv import *) from another Python file, I get the following error message: OSError: dlopen(/usr/local/lib/libcv.dylib, 6): Symbol not found: __ZN2cv10fastMallocEm Referenced from: /usr/local/lib/libcv.dylib Expected in: flat namespace And some more Python errors: module body in __init__.py at line 18 from ctypes_opencv.cxcore import * module body in cxcore.py at line 80 _cxDLL, _cvDLL, _hgDLL = detect_opencv() function detect_opencv in cxcore.py at line 59 cvDLL = cdll.LoadLibrary(find_lib('cv')) function LoadLibrary in __init__.py at line 431 return self._dlltype(name) function __init__ in __init__.py at line 353 self._handle = _dlopen(self._name, mode) I most recently built OpenCV using flags the ctypes_opencv wiki recommended: ENABLE_SSE(2) OFF and BUILD_NEW_PYTHON_SUPPORT OFF. I've tried a number of flag combinations though. I also tried using the MacPorts install of OpenCV, got the same messages, uninstalled it, and now it errors out as well. :P And if that wasn't enough, I tried using the latest ctypes wrapper, but get boost-jam errors. Any help would be very much appreciated.

    Read the article

  • Python3k ctypes printf

    - by dsaccount1
    printf returns 1 instead of Hello World! which is the desired result. I googled it and think its because of the changes in the way sequences are treated. Python-3000 Possible py3k problem resolved. import ctypes msvcrt=ctypes.cdll.msvcrt string=b"Hello World!" msvcrt.printf("%s", string)

    Read the article

  • efficiently convert string (or tuple) to ctypes array

    - by Mu Mind
    I've got code that takes a PIL image and converts it to a ctypes array to pass out to a C function: w_px, h_px = img.size pixels = struct.unpack('%dI'%(w_px*h_px), img.convert('RGBA').tostring()) pixels_array = (ctypes.c_int * len(pixels))(*pixels) But I'm dealing with big images, and unpacking that many items into function arguments seems to be noticeably slow. What's the simplest thing I can do to get a reasonable speedup? I'm only converting to a tuple as an intermediate step, so if it's unnecessary, all the better.

    Read the article

  • Building a ctypes-"based" C library with distutils

    - by Robie Basak
    Following this recommendation, I have written a native C extension library to optimise part of a Python module via ctypes. I chose ctypes over writing a CPython-native library because it was quicker and easier (just a few functions with all tight loops inside). I've now hit a snag. If I want my work to be easily installable using distutils using python setup.py install, then distutils needs to be able to build my shared library and install it (presumably into /usr/lib/myproject). However, this not a Python extension module, and so as far as I can tell, distutils cannot do this. I've found a few references to people other people with this problem: Someone on numpy-discussion with a hack back in 2006. Somebody asking on distutils-sig and not getting an answer. Somebody asking on the main python list and being pointed to the innards of an existing project. I am aware that I can do something native and not use distutils for the shared library, or indeed use my distribution's packaging system. My concern is that this will limit usability as not everyone will be able to install it easily. So my question is: what is the current best way of distributing a shared library with distutils that will be used by ctypes but otherwise is OS-native and not a Python extension module? Feel free to answer with one of the hacks linked to above if you can expand on it and justify why that is the best way. If there is nothing better, at least all the information will be in one place.

    Read the article

  • Python ctypes in_dll string assignment

    - by ackdesha
    I could use some help assigning to a global C variable in DLL using ctypes. The following is an example of what I'm trying: test.c contains the following #include <stdio.h> char name[60]; void test(void) { printf("Name is %s\n", name); } On windows (cygwin) I build a DLL (Test.dll) as follows: gcc -g -c -Wall test.c gcc -Wall -mrtd -mno-cygwin -shared -W1,--add-stdcall-alias -o Test.dll test.o When trying to modify the name variable and then calling the C test function using the ctypes interface I get the following... >>> from ctypes import * >>> dll = windll.Test >>> dll <WinDLL 'Test', handle ... at ...> >>> f = c_char_p.in_dll(dll, 'name') >>> f c_char_p(None) >>> f.value = 'foo' >>> f c_char_p('foo') >>> dll.test() Name is Name is 48+? 13 Why does the test function print garbage in this case?

    Read the article

  • Python Ctypes Read/WriteProcessMemory() - Error 5/998 Help!

    - by user299805
    Please don't get scared but the following code, if you are familiar with ctypes or C it should be easy to read. I have been trying to get my ReadProcessMemory() and WriteProcessMemory() functions to be working for so long and have tried almost every possibility but the right one. It launches the target program, returns its PID and handle just fine. But I always get a error code of 5 - ERROR_ACCESS_DENIED. When I run the read function(forget the write for now). I am launching this program as what I believe to be a CHILD process with PROCESS_ALL_ACCESS or CREATE_PRESERVE_CODE_AUTHZ_LEVEL. I have also tried PROCESS_ALL_ACCESS and PROCESS_VM_READ when I open the handle. I can also say that it is a valid memory location because I can find it on the running program with CheatEngine. As for VirtualQuery() I get an error code of 998 - ERROR_NOACCESS which further confirms my suspicion of it being some security/privilege problem. Any help or ideas would be very appreciated, again, it's my whole program so far, don't let it scare you =P. from ctypes import * from ctypes.wintypes import BOOL import binascii BYTE = c_ubyte WORD = c_ushort DWORD = c_ulong LPBYTE = POINTER(c_ubyte) LPTSTR = POINTER(c_char) HANDLE = c_void_p PVOID = c_void_p LPVOID = c_void_p UNIT_PTR = c_ulong SIZE_T = c_ulong class STARTUPINFO(Structure): _fields_ = [("cb", DWORD), ("lpReserved", LPTSTR), ("lpDesktop", LPTSTR), ("lpTitle", LPTSTR), ("dwX", DWORD), ("dwY", DWORD), ("dwXSize", DWORD), ("dwYSize", DWORD), ("dwXCountChars", DWORD), ("dwYCountChars", DWORD), ("dwFillAttribute",DWORD), ("dwFlags", DWORD), ("wShowWindow", WORD), ("cbReserved2", WORD), ("lpReserved2", LPBYTE), ("hStdInput", HANDLE), ("hStdOutput", HANDLE), ("hStdError", HANDLE),] class PROCESS_INFORMATION(Structure): _fields_ = [("hProcess", HANDLE), ("hThread", HANDLE), ("dwProcessId", DWORD), ("dwThreadId", DWORD),] class MEMORY_BASIC_INFORMATION(Structure): _fields_ = [("BaseAddress", PVOID), ("AllocationBase", PVOID), ("AllocationProtect", DWORD), ("RegionSize", SIZE_T), ("State", DWORD), ("Protect", DWORD), ("Type", DWORD),] class SECURITY_ATTRIBUTES(Structure): _fields_ = [("Length", DWORD), ("SecDescriptor", LPVOID), ("InheritHandle", BOOL)] class Main(): def __init__(self): self.h_process = None self.pid = None def launch(self, path_to_exe): CREATE_NEW_CONSOLE = 0x00000010 CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000 startupinfo = STARTUPINFO() process_information = PROCESS_INFORMATION() security_attributes = SECURITY_ATTRIBUTES() startupinfo.dwFlags = 0x1 startupinfo.wShowWindow = 0x0 startupinfo.cb = sizeof(startupinfo) security_attributes.Length = sizeof(security_attributes) security_attributes.SecDescriptior = None security_attributes.InheritHandle = True if windll.kernel32.CreateProcessA(path_to_exe, None, byref(security_attributes), byref(security_attributes), True, CREATE_PRESERVE_CODE_AUTHZ_LEVEL, None, None, byref(startupinfo), byref(process_information)): self.pid = process_information.dwProcessId print "Success: CreateProcess - ", path_to_exe else: print "Failed: Create Process - Error code: ", windll.kernel32.GetLastError() def get_handle(self, pid): PROCESS_ALL_ACCESS = 0x001F0FFF PROCESS_VM_READ = 0x0010 self.h_process = windll.kernel32.OpenProcess(PROCESS_VM_READ, False, pid) if self.h_process: print "Success: Got Handle - PID:", self.pid else: print "Failed: Get Handle - Error code: ", windll.kernel32.GetLastError() windll.kernel32.SetLastError(10000) def read_memory(self, address): buffer = c_char_p("The data goes here") bufferSize = len(buffer.value) bytesRead = c_ulong(0) if windll.kernel32.ReadProcessMemory(self.h_process, address, buffer, bufferSize, byref(bytesRead)): print "Success: Read Memory - ", buffer.value else: print "Failed: Read Memory - Error Code: ", windll.kernel32.GetLastError() windll.kernel32.CloseHandle(self.h_process) windll.kernel32.SetLastError(10000) def write_memory(self, address, data): count = c_ulong(0) length = len(data) c_data = c_char_p(data[count.value:]) null = c_int(0) if not windll.kernel32.WriteProcessMemory(self.h_process, address, c_data, length, byref(count)): print "Failed: Write Memory - Error Code: ", windll.kernel32.GetLastError() windll.kernel32.SetLastError(10000) else: return False def virtual_query(self, address): basic_memory_info = MEMORY_BASIC_INFORMATION() windll.kernel32.SetLastError(10000) result = windll.kernel32.VirtualQuery(address, byref(basic_memory_info), byref(basic_memory_info)) if result: return True else: print "Failed: Virtual Query - Error Code: ", windll.kernel32.GetLastError() main = Main() address = None main.launch("C:\Program Files\ProgramFolder\Program.exe") main.get_handle(main.pid) #main.write_memory(address, "\x61") while 1: print '1 to enter an address' print '2 to virtual query address' print '3 to read address' choice = raw_input('Choice: ') if choice == '1': address = raw_input('Enter and address: ') if choice == '2': main.virtual_query(address) if choice == '3': main.read_memory(address) Thanks!

    Read the article

  • Ctypes pro and con

    - by phreaki
    I have heard that Ctypes can cause crashes (or stop errors) in Python and windows. Should I stay away from their use? Where did I hear? It was back when I tried to control various aspects of windows, automation, that sort of thing. I hear of swig, but I see Ctypes more often than not. Any danger here? If so, what should I watch out for? I did search for ctype pro con python.

    Read the article

  • Python objects as userdata in ctypes callback functions

    - by flight
    The C function myfunc operates on a larger chunk of data. The results are returned in chunks to a callback function: int myfunc(const char *data, int (*callback)(char *result, void *userdata), void *userdata); Using ctypes, it's no big deal to call myfunc from Python code, and to have the results being returned to a Python callback function. This callback work fine. myfunc = mylib.myfunc myfunc.restype = c_int myfuncFUNCTYPE = CFUNCTYPE(STRING, c_void_p) myfunc.argtypes = [POINTER(c_char), callbackFUNCTYPE, c_void_p] def mycb(result, userdata): print result return True input="A large chunk of data." myfunc(input, myfuncFUNCTYPE(mycb), 0) But, is there any way to give a Python object (say a list) as userdata to the callback function? In order to store away the result chunks, I'd like to do e.g.: def mycb(result, userdata): userdata.append(result) userdata=[] But I have no idea how to cast the Python list to a c_void_p, so that it can be used in the call to myfunc. My current workaround is to implement a linked list as a ctypes structure, which is quite cumbersome.

    Read the article

  • C Class Instance from Void Pointer using Ctypes

    - by g.d.d.c
    I've got a C DLL that exposes a handful of methods that return void pointers to a Class like so: void *GetLicense() { static AppLicenseImpl ipds_; return (void *) &ipds_; } In C++, after loading the DLL, I'd do this to work with it: typedef void *(* FPGetLicense)(); GetLicense_ = (FPGetLicense)GetAddress("GetLicense"); license_ = (AppLicense *) GetLicense_(); license_->GetApplicationStatus(); // Load data so that other calls don't fail I can't figure out how to parallel that in Python. This gets me the pointer: d = ctypes.cdll.LoadLibrary('license.dll') d.GetLicense.restype = ctypes.c_void_p p = d.GetLicense() # returns ptr loc, something like 8791433660848L But I obviously can't call p.GetApplicationStatus() in Python. Does anyone have a suggestion on how I'd instantiate that Class the rest of the way in Python so that I can call GetApplicationStatus()?

    Read the article

  • Python ctypes: loading DLL from from a relative path

    - by Frederick
    I have a Python module, wrapper.py, that wraps a C DLL. The DLL lies in the same folder as the module. Therefore, I use the following code to load it: myDll = ctypes.CDLL("MyCDLL.dll") This works if I execute wrapper.py from its own folder. If, however, I run it from elsewhere, ctypes goes looking for DLL in the current working directory and naturally fails. My question is, is there a way by which I can specify the DLL's path relative to the wrapper instead of the current working directory? This will enable me to ship the two together and allow the user to run/import the wrapper from anywhere.

    Read the article

  • numpy calling sse2 via ctypes

    - by Daniel
    Hello, In brief, I am trying to call into a shared library from python, more specifically, from numpy. The shared library is implemented in C using sse2 instructions. Enabling optimisation, i.e. building the library with -O2 or –O1, I am facing strange segfaults when calling into the shared library via ctypes. Disabling optimisation (-O0), everything works out as expected, as is the case when linking the library to a c-program directly (optimised or not). Attached you find a snipped which exhibits the delineated behaviour on my system. With optimisation enabled, gdb reports a segfault in __builtin_ia32_loadupd (__P) at emmintrin.h:113. The value of __P is reported as optimised out. test.c: #include <emmintrin.h> #include <complex.h> void test(const int m, const double* x, double complex* y) { int i; __m128d _f, _x, _b; double complex f __attribute__( (aligned(16)) ); double complex b __attribute__( (aligned(16)) ); __m128d* _p; b = 1; _b = _mm_loadu_pd( (double *) &b ); _p = (__m128d*) y; for(i=0; i<m; ++i) { f = cexp(-I*x[i]); _f = _mm_loadu_pd( (double *) &f ); _x = _mm_loadu_pd( (double *) &x[i] ); _f = _mm_shuffle_pd(_f, _f, 1); *_p = _mm_add_pd(*_p, _f); *_p = _mm_add_pd(*_p, _x); *_p = _mm_mul_pd(*_p,_b); _p++; } return; } Compiler flags: gcc -o libtest.so -shared -std=c99 -msse2 -fPIC -O2 -g -lm test.c test.py: import numpy as np import os def zerovec_aligned(nr, dtype=np.float64, boundary=16): '''Create an aligned array of zeros. ''' size = nr * np.dtype(dtype).itemsize tmp = np.zeros(size + boundary, dtype=np.uint8) address = tmp.__array_interface__['data'][0] offset = boundary - address % boundary return tmp[offset:offset + size].view(dtype=dtype) lib = np.ctypeslib.load_library('libtest', '.' ) lib.test.restype = None lib.test.argtypes = [np.ctypeslib.ctypes.c_int, np.ctypeslib.ndpointer(np.float64, flags=('C', 'A') ), np.ctypeslib.ndpointer(np.complex128, flags=('C', 'A', 'W') )] n = 13 y = zerovec_aligned(n, dtype=np.complex128) x = np.ones(n, dtype=np.float64) # x = zerovec_aligned(n, dtype=np.float64) # x[:] = 1. lib.test(n,x,y) My system: Ubuntu Linux i686 2.6.31-22-generic Compiler: gcc (Ubuntu 4.4.1-4ubuntu9) Python: Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) [GCC 4.4.1] Numpy: 1.4.0 I have taken provisions (cf. python code) that y is aligned and the alignment of x should not matter (I think; explicitly aligning x does not solve the problem though). Note also that i use _mm_loadu_pd instead of _mm_load_pd when loading b and f. For the C-only version _mm_load_pd works (as expected). However, when calling the function via ctypes using _mm_load_pd always segfaults (independent of optimisation). I have tried several days to sort out this issue without success ... and I am on the verge beating my monitor to death. Any input welcome. Daniel

    Read the article

  • PythonMagickWand Shepards Distortion (ctypes LP_c_double problem)

    - by betamax
    I am trying to use PythonMagickWand to use a Shepards distortion on an image. You can also see the source of distort.c that is used by ImageMagick. I have the following code (snippet): from PythonMagickWand import * arrayType = c_double * 8 pointsNew = arrayType() pointsNew[0] = c_double(eyeLeft[0]) pointsNew[1] = c_double(eyeLeft[1]) pointsNew[2] = c_double(eyeLeftDest[0]) pointsNew[3] = c_double(eyeLeftDest[1]) pointsNew[4] = c_double(eyeRight[0]) pointsNew[5] = c_double(eyeRight[1]) pointsNew[6] = c_double(eyeRightDest[0]) pointsNew[7] = c_double(eyeRightDest[1]) MagickWandGenesis() wand = NewMagickWand() MagickReadImage(wand,path_to_image+'image_mod.jpg') MagickDistortImage(wand,ShepardsDistortion, 8, pointsNew, False) MagickWriteImage(wand,path_to_image+'image_mod22.jpg') I get the following error: MagickDistortImage(wand,ShepardsDistortion, 8, pointsNew, False) ctypes.ArgumentError: argument 4: <type 'exceptions.TypeError'>: expected LP_c_double instance instead of list I am aware that pointsNew is the wrong way of providing the arguments.. But I just don't know what is the right format. This is an example distort command that works when run in Terminal: convert image.jpg -virtual-pixel Black -distort Shepards 121.523809524,317.79638009 141,275 346.158730159,312.628959276 319,275 239.365079365,421.14479638 232,376 158.349206349,483.153846154 165,455 313.015873016,483.153846154 300,455 0,0 0,0 0,571.0 0,571.0 464.0,571.0 464.0,571.0 0,571.0 0,571.0 image_out.jpg So I guess the question is: How do I create a list of c_doubles that will be accepted by PythonMagickWand? I basically need to re-create the terminal command. I have got it working by using subprocess to run the command from Python but that is not how I want to do it.

    Read the article

1 2 3  | Next Page >