Menu
  • HOME
  • TAGS

ctypes call GetProcAddress() failed with error code 127,but win32api.GetProcAddress successed

python,ctypes

You need to use a char string rather than the default Unicode string provided by python 3.x, as hinted by the GetProcAddress documentation (the 2nd parameter is a LPCSTR, not LPCTSTR or LPCWSTR): h_loadlib2 = KERNEL32.GetProcAddress(h_kernel32,'LoadLibraryW'.encode(encoding='ascii')) Alternatively, you can pass a byte: h_loadlib2 = KERNEL32.GetProcAddress(h_kernel32, b'LoadLibraryW') Note: The above code...

Interfacing cuSOLVER-sparse using PyCUDA

python,cuda,ctypes,pycuda,cusolver

Setting descrA to ctypes.c_void_p() and replacing cusparseMatDescr_t in the cusolverSpDcsrlsvqr wrapper with ctypes.c_void_p should solve the problem.

Why is my ctypes long size 4 and not size 8 using 64 bit python?

python,ctypes,anaconda

A long is only guaranteed to be at least 32 bits wide, so on some systems, ctypes.c_long is only 32 bits. In particular, I believe on 64-bit Windows, ctypes.c_long is only 32 bits wide. If it must be 64 bits wide, use ctypes.c_int64 instead.

numpy ctypes “dynamic module does not define init function” error if not recompiled each time

python,c++,numpy,ctypes

Try running import imp; print imp.find_module('mylib')[1]. Are you surprised that it picks mylib.so instead of mylib.py? The interpreter expects mylib.so to be an extension module, which for CPython 2.x should define an initialization function named initmylib. To avoid accidentally trying to import the shared library, either change the name to...

python-magic WindowsError: access violation writing 0x00000000

python-2.7,cygwin,ctypes,python-magic

The GnuWin32 file package has a 32-bit magic1.dll, along with its dependencies regex2.dll and zlib1.dll. I know from testing that this version works with python-magic. Here's an overview of the steps that I took to test this in 32-bit Python 3.3. Extract the files to GnuWin32's installation directory: C:\Temp>set "GNU=C:\Program...

Python ctypes for HANDLE

python,dll,ctypes

Try redefining the function call like this: from ctypes import * from ctypes.wintypes import * dll = WinDLL('myDll.dll') connect = dll.Connect connect.restype = c_short connect.argtypes = [POINTER(HANDLE), POINTER(UINT), LPCWSTR, LPCWSTR, c_int, c_int) And call like this, using byref to pass by reference: self.user_id = HANDLE() self.keep_alive_id = UINT() err =...

Invalid input type for c_char ctypes in python

python,c,header,ctypes

The signature of your function is (const char arg1 ... ) so you must pass a char as first argument and not a character. That means a byte and not a single char string. To test it I wrote my lib foo.c #include <stdio.h> void foo(const char v) { printf("Hello,...

Python ctypes : OSError undefined symbol when loading library

python,c,ctypes

When I use your compilation line I get five warnings. There are several problems here. First you are trying to assign an int to void * in several places. That raises a warning, and it would crash at runtime because you are passing 2 and 3 as addresses. Second, you...

python ctypes how to map PTSTR

python,winapi,ctypes

Is it just: filename = ctypes.c_char_p('something') filename = ctypes.c_wchar_p('something') # for unicode Edit: answer was based on the definition of PWSTR, PSTR, and PTSTR on this page and the ctypes docs. And as suggested in the comments you should use restype/argtypes, especially if you are trying to be explicit, something...

Increment Reference Counter for a CFUNCTYPE

python,c,ctypes

cback is a function that returns a wrapped function. What else works that way? Decorators: # global scope, the callback type cback = ctypes.CFUNCTYPE(None,ctypes.POINTER(problem)) # decorate the callback @cback def change_struct_data(s): s.contents.val = 99 Now change_struct_data is actually an instantiated CFUNCTYPE object that will not go out of scope. You...

Speeding up Python with C++

python,c++,ctypes

I would go with this: template<class MeanT, class AccumT = MeanT, class IterT> MeanT mean_squares(IterT start, IterT end) { AccumT accum = 0; for (IterT it = start; it != end; ++it) { accum += *it * *it; } return accum / (end - start); } I left out the...

WindowsError exception access violation - in simple python c++ ctypes interface

python,c++,ctypes

After noticing other problems it turned out that the configuration of my compiler was the issue, and a reinstall / different compiler allowed this code to run.

python 3.3 dict: how to convert struct PyDictKeysObject to python class?

python,c,python-3.x,dictionary,ctypes

My problem was to access the C struct underlying a python dictionary implemented in Cpython 3.3. I started with the C structs provided in cpython/Objects/dictobject.c and Include/dictobject.h . Three C structs are involved in defining the dictionary: PyDictObject, PyDictKeysObject, and PyDictKeyEntry. The correct translation of each C struct into python...

Passing a Python Object to C module

python,ctypes

No, you can't pass pure Python objects to C that way. However, you can declare a ctypes.Structure or ctypes.Union type and pass that to a c function as if it were a C struct or union, usually with a POINTER. Example from the docs: from ctypes import * class POINT(Structure):...

Memory Leak in Ctypes method

python,c,memory-leaks,ctypes

Since the images are being returned as pointers to buffers stbi_load must be allocating space for them and you are not releasing this space before returning so the memory leak is not surprising. Check for the documentation to see if there is a specific stpi_free function or try adding free(image1);...

OCaml Ctypes and allocating a pointer to a type

ocaml,ctypes

In order to allocate something you need to know its size. In the libyaml library the yaml_parser_t type is not opaque, so the most correct way to work with such type, would be to declare it in ctypes as a struct and describe all its fields. In that case, you...

How do I cast to a constant in ctypes?

python,c++,ctypes

pos = C.POINTER(C.c_double) creates a type. You want an instance of a c_double and pass the address to the function: d = C.c_double(2.0) GCS_api.PI_MOV(controller_number, szAxis1, C.byref(d)) Since the function may want an array of doubles, this is the syntax for that: d = (C.c_double*4)(1.1,2.2,3.3,4.4) # Create double[4] array ...

Return double array through FORTRAN (DLL) to process further in python

python,dll,fortran,ctypes,fortran77

After some tooling around; also thanks to the valuable suggestions by Vladimir F, a solution to the issue as described above has been found. Some slight changes on the python side of things were required in order to make it work: import ctypes as cs import numpy as np #import...

Converting .so file of linux to a .dll file of windows

c,dll,ctypes

I'd recommend to recompile it on windows, alternatively you can give a try to dlltool.

More cttypes c_float() precision

python,floating-point,ctypes,floating-accuracy

Jan Rüegg is right - this is just how floats work. If you're wondering why this only shows up with c_float, it's because c_floats print as "c_float({!r}).format(self.value). self.value is a double-precision Python float. Python's float type prints the shortest representation that converts to the floating point number, so although float(0.2)...

Use Security.framework types from Python

python,osx,cocoa,ctypes

I'm looking into case #2, because it seems simpler. Your CFDictionarySetValue is missing the dict argument. After fixing that, it appears that security.kSecClass is actually returning a function reference, which is bad. I think you need to: ctypes.c_void_p.in_dll(foundation, 'kSecClass') Which results in the correct value being passed to the function...

Pass Python list to embedded Rust function

python,rust,ctypes

Don't do this: #[no_mangle] pub extern fn my_func(my_vec: Vec<i32>) -> i32 { ... } You basically never want to accept or return an arbitrary Rust object in an extern function, only ones that are Repr. Instead, you should accept something that is representable by C. As 6502 says, the best...

Using windll in ctypes on Windows 7 (64bit)

python,python-2.7,ctypes

The error message appears while short script described in comments (proposed by jedwards) is run under mobaxterm terminal. When the script is ran in cmd.exe console, no errors appears. Thanks, guys, for heads up......

Undefined symbol with Python extention using OpenCV C API

python,c,opencv,gcc,ctypes

Switching to C++ solves the problem. Luckily I have the flexibility.

Passing a list of strings from Python to Rust

python,rust,ctypes,ffi

There is absolutely no difference with the case of array of numbers. C strings are zero-terminated arrays of bytes, so their representation in Rust will be *const c_char, which could then be converted to &CStr which then can be used to obtain &[u8] and then &str. Python: import ctypes rustLib...

NotADirectoryError from ctypes with matplotlib and cx_Freeze

python,python-3.x,matplotlib,ctypes,cx-freeze

Imported matplotlib (especially its import of numpy) changes OSError: The specified module could not be found from ctypes to NotADirectoryError: [WinError 267] The directory name is invalid in frozen scripts. That's all. If the DLL is installed everything works fine. If matplotlib is not imported, you get an OSError: The...

rsvg python memory leak in osx (ctypes?)

python,svg,ctypes,cairo,pycairo

According to the documentation of rsvg_handle_new, free the handle with g_object_unref. Also, if a failed call allocates a GError, after you get the code and message you have to free the error with g_error_free. from ctypes import * from ctypes.util import find_library _gobj = CDLL(find_library("gobject-2.0")) _glib = CDLL(find_library("glib-2.0")) class _GError(Structure):...

Cannot get pi from a c library called from python using ctypes

python-3.x,ctypes

From the Return Types documentation: By default functions are assumed to return the C int type. Other return types can be specified by setting the restype attribute of the function object. So you should do: myModule.ppi.restype = c_double print(myModule.ppi(1)) print(myModule.ppi(2)) ...

does python ctypes supports size-0 array?

python-3.x,ctypes

You can represent a struct like this: struct Test { int size; char arr[0]; }; As: class Test(ctypes.Structure): _fields_ = [('size',ctypes.c_int), ('arr',ctypes.c_byte*0)] But to access the field, you'll need to cast it to a pointer. Assume t is of type ctypes.POINTER(Test): arr = ctypes.cast(t.contents.arr,POINTER(c_byte)) for i in range(t.contents.size): print(arr[i]) Tested...

Trying to call wincred api using ctypes

python,ctypes,advapi32

oledll should be windll. oledll is used for functions that return HRESULT. The definition of CREDENTIAL is missing some fields (LastWritten and Persist). The definition (link) is: typedef struct _CREDENTIAL { DWORD Flags; DWORD Type; LPTSTR TargetName; LPTSTR Comment; FILETIME LastWritten; DWORD CredentialBlobSize; LPBYTE CredentialBlob; DWORD Persist; DWORD AttributeCount; PCREDENTIAL_ATTRIBUTE...

Ctypes How to set OSType which expects characters but is defined as unsigned int (OSX)

python,osx,ctypes,core-foundation

const OSType kFinderSig = 'MACS'; 'MACS' is a character constant, not a string! This code is using a (questionable) GCC extension for multi-character character constants. You can reproduce the results in Python using the (builtin) struct module: import struct kFinderSig = struct.unpack(">L", "MACS")[0] Alternatively, just hard-code the value as 0x4d414353...

Convert Rust vector of tuples to a C compatible structure

python,rust,ctypes

The most important thing to note is that there is no such thing as a tuple in C. C is the lingua franca of library interoperability, and you will be required to restrict yourself to abilities of this language. It doesn't matter if you are talking between Rust and another...

kernel32.CreateProcessW: Python crashes after successful launch when trying to access PROCESS_INFORMATION structure

python,python-3.x,ctypes

Your struct definitions assign to _fields instead of the correct attribute name _fields_. To help catch a typo like this, define __slots__ = '__weakref__'. This prevents instances from getting a __dict__, but it retains the ability to create weak references. Of course, it's still a problem if you have a...

Why won't this ctypes code work with Python 3.3 but will work with Python 2.7?

python,windows-7,ctypes

SystemParametersInfoA requires a 8-bit ANSI encoded input string as a parameter, which is known as mbcs encoding in Python. You will have to use SystemParametersInfoW in python3. This is because SystemParametersInfoW takes in a UTF-16 wide string (which is wchar_t * in C) and the ctypes library automatically converts this...

Access np.array in ctypes struct

python,numpy,ctypes

One way to do what you are talking about would be to just straight up allocate the numpy array on the python side and behave like it is a straight forward double array on the C side. import numpy as np import ctypes as C # allocate this as a...

Passing a path to Labview DLL in Python

python,dll,ctypes,labview

Slashes go the other way in the path variable evaluate to LabVIEW "not a path" and as rightfully pointed out above, python3 requires to use the "b" prefix.

How to stop memory leaks when using `as_ptr()`?

python,memory-leaks,rust,ctypes,ffi

Your Rust function do_something constructs a temporary CString, takes a pointer into it, and then drops the CString. The *const c_char is invalid from the instant you return it. If you're on nightly, you probably want CString#into_ptr instead of CString#as_ptr, as the former consumes the CString without deallocating the memory....

After partition was created using IOCTL_DISK_SET_DRIVE_LAYOUT, how do I create new volume in this newly created partition?

python,ctypes,ioctl

Long story short (it really is a long story!), turn out, I mistakenly choose a wrong PartitionType. Previously I use PARTITION_EXTENDED 0x05, which after I experiment with another value : PARTITION_IFS 0x07, Windows directly asked me to format the partition. And to avoid this, as asked here, we have to...

C function called via Python determines wrong array size

python,c,arrays,ctypes

The quite newbee problem of sizeof() has already pointed out in comment. Well, in order to answer your question How do I make the C code recognize the proper size of these arrays and/or make the Python pass "knowledge" of the array size to the C code. I tried to...

Dynamically create Ctypes in Python

python,dynamic,ctypes

Solution 2 is probably your better option, though if you're also writing such classes statically, you may want to use a metaclass to deduplicate some of that code. If you need your objects to be pickleable, then you'll need a way to reconstruct them from pickleable objects. Once you've implemented...

Python ctypes UnicodeEncodeError

python,windows,encoding,ctypes

import ctypes, time GetForegroundWindow = ctypes.windll.user32.GetForegroundWindow GetWindowTextLength = ctypes.windll.user32.GetWindowTextLengthW GetWindowText = ctypes.windll.user32.GetWindowTextW WriteConsoleW = ctypes.windll.kernel32.WriteConsoleW STD_OUTPUT_HANDLE = - 11 outhandle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE) while True: time.sleep(1) act_id = GetForegroundWindow() length = GetWindowTextLength(act_id) buff = ctypes.create_unicode_buffer(length + 1) GetWindowText(act_id, buff, length + 1) chars_written =...

Import error with ctypes in python27, segmentation fault

python,ctypes

This is a known bug in read only filesystems, in this thread you can find a patch along with more information.

Setting _fields_ dynamically in ctypes.Structure

python,ctypes

Yes. This is the function that would generate the Int class: def int_factory(fields): return type("Int", (Structure,), {"_fields_": fields}) and this is how you would call it: def user(values=[1,2]): int_fields = (("first_16", c_int, 16),("second_16", c_int, 16)) # this is just an example to illustrate your class definition. int fields can be...

Ctypes create_string_buffer gives raise TypeError(init)

python,ctypes

I am confused. Is testUpdate(p_path) supposed to call a C function? It looks like it recursively calls the python code (with the wrong parameter type). Try to rename the Python function. BTW, Your C code is faulty. I suppose what you want is char * testUpdate(const char * softwareToolsPath) {...

How can ctypes be used to parse unicode strings?

python,string,unicode,ctypes

C/C++ has no real support for Unicode, so there really isn't anything you can do about it. You must to encode your string as in order to pass them into the C/C++ world: you could use UTF-8, UTF-16, or UTF-32 depending on your use case. For example, you can encode...

Value conversion between ctypes and python is wrong

python,c,ctypes

long arr[2] is a local array on the stack. Returning the address of that array is undefined behavior. You could make the array static long arr[2] and it would work....

Using C from Python

python,c,ctypes,network-interface

Is this good? Almost. Never return 0/null as a PyObject* unless you're signaling an exception; instead incref Py_None and return it. And you may want to add actual error checking code as well. And what are the steps to importing it into Python with ctypes? How can I do...

c_void_p arguments in callbacks using ctypes in Python

python,callback,ctypes

Receiving a c_void_p as an integer in the callback is normal. It's using the simple type's getfunc to do the automatic conversion -- same as getting a c_void_p as a Structure field. ctypes won't do automatic conversion for a subclass of a simple type -- e.g. type('my_void_p', (c_void_p,), {}). Though...

Unable to access value of const char array

python,c,string,segmentation-fault,ctypes

@eryksun pointed out that the restype of the C function was defaulting to int and being resolved to a Python integer. By calling mylib.get_mystr.restype = c_char_p, it now properly resolves to a bytes object which can be decoded properly....

What does pythonapi.PyObject_GC_UnTrack return?

python,c,memory-management,garbage-collection,ctypes

From the ctypes docs: ctypes.pythonapi An instance of PyDLL that exposes Python C API functions as attributes. Note that all these functions are assumed to return C int, which is of course not always the truth, so you have to assign the correct restype attribute to use these functions. And...

Issues with Python ctypes '_as_parameter_' and 'from_param' on OS X

python,c,osx,ctypes,ffi

The getfunc of c_void_p returns the pointer value as an integer. The default conversion for an integer argument is a C int, which truncates a 64-bit pointer value. There are at least two ways to deal with this. Either wrap the integer result in c_void_p. class GFF3OutStream(GenomeStream): def __init__(self, genome_stream):...

Is this a global?

c,ctypes

As the others mentioned before display is a static variable. The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables...

ctypes own library loads but can't access functions/methods

python,c++,linux,ctypes

You have two problems: Firstly as has already been noted tab auto-complete won't work for ctypes until a function has been used for the first time. (It wouldn't be impossible to make it work on most platforms, but it would add a fair overhead to loading the library I suspect)....

ctypes error AttributeError symbol not found, OS X 10.7.5

python,c++,ctypes

Your first problem is C++ name mangling. If you run nm on your .so file you will get something like this: nm test.so 0000000000000f40 T __Z3funv U _printf U dyld_stub_binder If you mark it as C style when compiled with C++: #ifdef __cplusplus extern "C" char fun() #else char fun(void)...

ctypes

python,ctypes

The line c_time = ctypes.POINTER(ctypes.c_double * 7) declares a type. You need to pass an instance of a type to the C function call, not the type itself. Try replacing this line with c_time_type = ctypes.POINTER(ctypes.c_double * 7) c_time = c_time_type() (You could write c_time = ctypes.POINTER(ctypes.c_double * 7)() instead...

Get error message from ctypes windll

python,windows,python-2.7,ctypes

The ctypes documentation recommends using use_last_error=True to capture GetLastError() in a safe way. Note you need to retrieve the error code when raising WinError: from ctypes import * SPI_SETDESKWALLPAPER = 0x0014 SPIF_SENDCHANGE = 2 SPIF_UPDATEINIFILE = 1 def errcheck(result, func, args): if not result: raise WinError(get_last_error()) user32 = WinDLL('user32',use_last_error=True) SystemParametersInfo...

Available and Total RAM always the same

python,windows,memory,ctypes,ram

According to the note at the GlobalMemoryStatus MSDN entry: On Intel x86 computers with more than 2 GB and less than 4 GB of memory, the GlobalMemoryStatus function will always return 2 GB in the dwTotalPhys member of the MEMORYSTATUS structure. Similarly, if the total available memory is between 2...

Change focus to Tkinter program using system-wide hotkey

python,python-3.x,ctypes,pywin32

eryksun pointed out the problem - I was using the wrong case for the hotkey. ord("v") should have been ord("V").

Changing XWindow geometry

python,linux,python-3.x,x11,ctypes

As @Andrey Sidorov said I have to call XFlush() before display closing. Now works.

How to pass numpy array inside of struct to ctypes function?

python,numpy,ctypes

You can remove array_1d_double. It is not needed. The struct should be declared like this: class MyStruct(ctypes.Structure): _fields_ = [ ('n', ctypes.c_int), ('x', ctypes.POINTER(ctypes.c_double)) ] I've changed both types. You had c_int16, but the type you used in the C code is int. That maps to c_int. And likewise for...

python concatenate ctype struct and array

python,arrays,concatenation,ctypes

You can copy the header struct into a ctypes array of bytes: >>> buf = (ctypes.c_char * ctypes.sizeof(header)).from_buffer_copy(header) Now, in Python 2, >>> buf.raw + sdata.tostring() should give you what you're looking for. In Python 3, it would be >>> buf.raw + sdata.tobytes() ...

Pasting image from clipboard to MS Word has wrong aspect ratio

winapi,python-3.x,python-imaging-library,ctypes

The resolution of a windows bitmap is defined by the biXPelsPerMeter and biYPelsPerMeter members of the `BITMAPINFOHEADER' structure. The Python Imaging Library (PIL) writes the resolution as 1 pixel per meter in both directions (line 225 of BmpImagePlugin.py). Thus Word thinks the bitmap is hundreds of metres in size and...

Define array length for c_char Python

python,c,compilation,header,ctypes

To create arrays use: out_char = (ctypes.c_char * 41)() This creates an instance of an array object: >>> (ctypes.c_char*41)() <__main__.c_char_Array_41 object at 0x0000000002891048> You can access the individual elements: >>> out_char[0] b'\x00' >>> out_char[40] b'\x00' >>> out_char[41] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: invalid...

Format Drive in Python

python,windows,python-3.x,ctypes

I found the solution! This line: FMIFS_HARDDISK = 0x0C should be like this FMIFS_UNKNOWN = 0 That simply makes it format by Unknown!...

Portable ctypes.c_char_p for python 2.x and 3.x

python,ctypes

Those types are equivalent. In C strings are arrays or pointers to the char type (each char represented by one byte). In python 3 the closest data type is bytes. Strings in python 3 are encoded using UTF-8, so each char is not guaranteed to be exactly one byte. Whereas,...

using c++ code from python in a shared-lib to control an LCD

python,c++,shared-libraries,ctypes,raspberry-pi2

Because you're not familiar with C I assume you made the same mistake as I made for a while. You do not take care about name mangeling in C++. See http://en.wikipedia.org/wiki/Nm_%28Unix%29 Please show how the functions are exported. Additional information could be found here: Python: accessing DLL function using ctypes...

ctypes in python size with the `sys.getsizeof(Var)` method vs `ctypes.sizeof(Var)`

python,size,byte,ctypes,sys

If you want to know the details, you should take a look at objects.h (especially the comments at the top of the file). Your ctypes.c_byte(1) is a Python object: >>> import sys >>> import ctypes >>> isinstance(ctypes.c_byte(1), object) True As noted by @Daniel, sys.getsizeof gets the size of that Python...

Python MessageBox with Icons using ctypes and windll

python,dll,ctypes,messagebox

you just OR them together import ctypes MB_OK = 0x0 MB_OKCXL = 0x01 MB_YESNOCXL = 0x03 MB_YESNO = 0x04 MB_HELP = 0x4000 ICON_EXLAIM=0x30 ICON_INFO = 0x40 ICON_STOP = 0x10 result = ctypes.windll.user32.MessageBoxA(0, "Your text?", "Your title", MB_HELP| MB_YESNO | ICON_STOP) I got the hex values from the documentation you linked...

Are python strings actually immutable on the hardware level?

python,c,string,ctypes

There are some computer systems where an arbitrary range of memory can be tagged as read-only at a hardware level, but that is not what is happening in python. What is happening is that by definition, python prevents strings being changed in place one created. Yes - it would be...

Get the value of a ctypes.c_ulong pointer?

python,ctypes

You mean, dereference b to get that c_ulong(20)? That's b.contents. Or do you mean, see where in memory that pointer happens to point, as if it was an integer rather than a pointer? That's ctypes.cast(b, ctypes.c_ulong) (if a pointer fits into a long on your platform).

fscanf does not work in a ctype python call

python,c,ctypes,fscanf

OP's file is a compressed file "GoogleNews-vectors-negative300.bin.gz" and code is designed to read the uncompressed version. Re-try with the uncompressed version....

Catch exception in ctypes based on C-exit code

python,c,ctypes

exit calles the system's exit function and terminates the process running, in your case ipython. The way error handling is done in C is by setting some global error variable and returning a status flag #include <math.h> char *error_string; extern char* get_error_string() { return error_string; } extern int cfun(double* A)...

Passing string to Fortran DLL using ctypes and Python

python,string,dll,fortran,ctypes

Following comment from @eryksun, I made the following changes to make it work. Changed the argtypes to: function2 = getattr(dll, 'FUNCTION2') function2.argtypes = [C.c_char_p, C.c_long, C.c_char_p, C.c_long, C.c_char_p, C.c_long, np.ctypeslib.ndpointer(C.c_long , flags='F_CONTIGUOUS'), np.ctypeslib.ndpointer(C.c_double, flags='F_CONTIGUOUS'), np.ctypeslib.ndpointer(C.c_long, flags='F_CONTIGUOUS')] And instead of passing the string as byref, I changed it to the following....

calling a dll function that takes a pointer to a handle (win32) from python

python,ctypes

It seems the function is using stdcall instead of the cdecl calling convention, i.e. use ctypes.WinDLL instead of ctypes.CDLL. Also, it wants a pointer to a memory location where it can store the handle, but you passed it a NULL pointer. Instead pass it a reference to a wintypes.HANDLE. from...

Python NtQueryDirectoryFile (File information structure)

python,python-3.x,ctypes,ntdll,nt-native-api

The following calls NtQueryDirectoryFile in a loop until it returns STATUS_NO_MORE_FILES. It doubles the buffer size if the system call returns STATUS_BUFFER_OVERFLOW or when the status is non-negative and the status block Information is 0. For each successful pass, the class method listbuf copies the individual FILE_DIRECTORY_INFORMATION structures out of...

How to define C-Enumeration types in python

python,ctypes,memmove

The Enumeration class suggested by Raj Kumar was broken in that it required the __init__ to be run to set a new value in a variable, and thus unusable if the value was changed on C side. Here is a fixed version thereof: class EnumerationType(type(c_uint)): def __new__(metacls, name, bases, dict):...

Python ctypes Unable to pass memory array in a structure

python,windows,dll,ctypes

First: when you initialize the WData object, the 6th argument is ctypes.POINTER(MemoryBuffer). This is (or should be syntactically) incorrect: Pointer returns a pointer type, while you need a unsigned char array (which is an object or an instance of a type). The size error that you get is because the...

Having trouble implementing a readlink() function

python,ctypes,symlink,junction,readlink

ERROR_MOD_NOT_FOUND (126) is likely due to windll.CloseHandle(hfile), which tries to load "closehandle.dll". It's missing kernel32. Here's an alternate implementation that handles junctions as well as symbolic links. from ctypes import * from ctypes.wintypes import * kernel32 = WinDLL('kernel32') LPDWORD = POINTER(DWORD) UCHAR = c_ubyte GetFileAttributesW = kernel32.GetFileAttributesW GetFileAttributesW.restype = DWORD...

Saving XML as ctypes c_byte in variable gives TypeError: an integer is required

python,c,xml,ctypes

A c_byte array takes a variable number of ints as argument, you're trying to give it a list. Try this instead: xml_bytes = bytearray(b'<xml>...') XMLparamsVal = (ctypes.c_byte*2049)(*xml_bytes) *xml_bytes is expanded to a series of positional int arguments. For python3, you wouldn't need the bytearray, you can use a byte literal...

Unable to load C++ dll in python

python,dll,ctypes

Based on your header, here's a dummy C file (for Windows) that can be used to test a ctypes wrapper. You mentioned C++ but the example was a C interface, which is a good thing because ctypes works with C functions not C++. x.c #include <stdio.h> struct FileParams { float...

python 'decode' has no attribute shellcode

python,python-3.x,ctypes,shellcode

In python3 sys.argv[1] would be a str (unicode, in python2) so there's nothing to decode. A simple test - arg_type.py: import sys shellcode = sys.argv[1] print(type(shellcode)) Run in python3 and python 2 $ python3.4 arg_type.py 'é' <class 'str'> $ python2.7 arg_type.py 'é' <type 'str'> Note that in the python2.7 str...

error when unload a 64bit dll using ctypes windll

python,64bit,ctypes

FreeLibrary takes a handle, defined as a C void * pointer. Refer to Windows Data Types. Set this in the function pointer's argtypes: from ctypes import * from ctypes.wintypes import * windll.kernel32.FreeLibrary.argtypes = [HMODULE] The default conversion of a Python int or long (renamed int in Python 3) is to...

Python ctypes with io.readinto doesn't work well

python,ctypes

As far as I understand, you're have trouble with structure packing. It looks like your code is reading "03 00 00 00 49 7B 00 00" (word size - 64bits) but only using the first 4 bytes "03 00 00 00". Update: According to eryksun, the analysis above is correct....

How can I setup a Structure in ctypes with pointer to itself?

python,ctypes

You may emulate C-style decleration followed by definition. see ctypes docs on incomplete types >>> class VNODE(Structure): # incomplete type / forward declaration ... pass ... >>> VNODE._fields_ = [("firstchar", c_char), ... ("wordlength", c_ubyte), ... ("is_red", c_bool), ... ("left", POINTER(VNODE)), ... ("right", POINTER(VNODE))] ...

Get address from PyCObject?

python,ctypes,python-2.6

Call PyCObject_AsVoidPtr: import ctypes PyCObject_AsVoidPtr = ctypes.PYFUNCTYPE(ctypes.c_void_p, ctypes.py_object)( ('PyCObject_AsVoidPtr', ctypes.pythonapi)) addr = PyCObject_AsVoidPtr(some_pyc_object) ...

ctype why specify argtypes

python,c++,ctypes

Yes, you should, because why it had worked is because of ctypes' guess. Replace int test_i(int i) with int test_i(char i), and you will get stack corruption — because Python side gives function 4 or 8 bytes, while C side only reads 1 byte. Depending on platform, this may go...

ctype - python - long int too long to convert -

python,ctypes

After a long time of fail and error I finally have an answer. from ctypes import * from ctypes.wintypes import * import ctypes OpenProcess = windll.kernel32.OpenProcess ReadProcessMemory = windll.kernel32.ReadProcessMemory CloseHandle = windll.kernel32.CloseHandle PROCESS_ALL_ACCESS = 0x1F0FFF pid = 2320 address = 0x00C98FCC buffer = c_char_p(b"The data goes here") val = c_int()...

Define array type in Python to be filled by C function

python,c,arrays,ctypes

Python code should be something that according to function definition: out_char = ctypes.c_char() result = lib.test(ctypes.byref(out_char)) ...

How do I call a delphi function that takes and returns pointers of custom type from Python?

python,delphi,pointers,dll,ctypes

I can see the following simple problems: Delphi Smallint is a signed 16 bit type. That matches up to c_short. Delphi Single is an IEEE-754 floating point value. That matches up to c_float. The Delphi type has an array of length 1001. Yours has length 10. The Delphi function has...

Python - ctypes - How to call functions and access struct fields?

python,c++,c,ctypes

Answering myself and sharing the knowledge with you: First, need to create a shared library from the C file: gcc -shared -fpic smart_string.c -o SmartString.so Then, use the following Python code (see comments for explanation about each done action): Note: char*, as appears in the above API is a C...

Python CDLL cannot load library 2 times

python,python-3.x,ctypes

In the comments you state that your DLL function call an API function that shows a file selection dialog. File selection dialogs, unless you tell them not to, can change the working directory. Since you failed to specify a full path to the DLL, the DLL search is performed each...

Using Rust returned array in Python using ctypes

python,rust,ctypes

As others have said, you can't really return a fixed-size array properly. But you can trick ctypes into doing the right thing by wrapping the array in a structure: import ctypes class Int32_4(ctypes.Structure): _fields_ = [("array", ctypes.c_int32 * 4)] lib = ctypes.CDLL("embed.dll") lib.make_array.restype = Int32_4 temp = lib.make_array() print(temp.array[:]) This...

What is the difference between id(obj) and ctypes.addressof(obj) in CPython

python,memory-management,ctypes

What you are suggesting should be the case is an implementation detail of CPython. The id() function: Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. CPython implementation detail: This is the address of the...

How to compare two ctypes objects for equality?

python,ctypes

Create a class MyCtStructure, then all its subclass do not need to implement __eq__ & __ne__. Defining eq would be not be a bit tedious job in your case anymore. import ctypes as ct class MyCtStructure(ct.Structure): def __eq__(self, other): for fld in self._fields_: if getattr(self, fld[0]) != getattr(other, fld[0]): return...