Ctypes download windows
It is included in the standard library for Python 2. It is even possible to implement C callback functions in pure Python. The ctypes tutorial and the ctypes documentation for Python provide extensive information on getting started with ctypes. The following sections cover some possible build scripts, C code and Python code.
SharedLibrary distutils extension included with OOF2. This should probably be included in numpy. You should be able to build the DLL with any version of the Visual Studio compiler regardless of the compiler used to compile Python. You can use the following file with SCons to build a shared library. When linking against a static library that contains foo, or when including foo in an executable, don't define anything.
Alternatively, you might prefer to write C code. In general, a C function might take a pointer to the array's data, an integer indicating the number of array dimensions, pass the value of the ndim property here and two int pointers to the shapes and stride information. If your C function assumes contiguous storage, you might want to wrap it with a Python function that calls! Starting with ctypes 0. Before ctypes calls a C function, it uses the argtypes list to check each parameter.
NumPy's ndpointer function, some very useful argtypes classes can be constructed, for example:. Now, if an argument doesn't meet the requirements, a! TypeError is raised.
This allows one to make sure that arrays passed to the C function is in a form that the function can handle. See also the mailing list thread on ctypes and ndpointer.
We can use this feature to allocate! NumPy arrays if and when we need a buffer for C code to operate on. This could avoid having to copy data in certain cases.
You also don't have to worry about freeing the C data after you're done with it. By allocating your buffers as! NumPy arrays, the Python garbage collector can take care of this.
Eventually, we'd like to write the allocator like this but it doesn't work yet :. Possible failures include a! SystemError exception being raised, the interpreter crashing or the interpreter hanging.
And the Python code:. The allocate function creates a new! There are, however, enough ways to crash Python with ctypes , so you should be careful anyway.
The faulthandler module can be helpful in debugging crashes e. None , integers, bytes objects and unicode strings are the only native Python objects that can directly be used as parameters in these function calls. Python integers are passed as the platforms default C int type, their value is masked to fit into the C type.
Before we move on calling functions with other parameter types, we have to learn more about ctypes data types. All these types can be created by calling them with an optional initializer of the correct type and value:. You should be careful, however, not to pass them to functions expecting pointers to mutable memory. The current memory block contents can be accessed or changed with the raw property; if you want to access it as NUL terminated string, use the value property:.
Note that printf prints to the real standard output channel, not to sys. As has been mentioned before, all Python types except integers, strings, and bytes objects have to be wrapped in their corresponding ctypes type, so that they can be converted to the required C data type:. You can also customize ctypes argument conversion to allow instances of your own classes be used as function arguments.
Of course, it must be one of integer, string, or bytes:. It is possible to specify the required argument types of functions exported from DLLs by setting the argtypes attribute. Specifying a format protects against incompatible argument types just as a prototype for a C function , and tries to convert the arguments to valid types:. 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. Here is a more advanced example, it uses the strchr function, which expects a string pointer and a char, and returns a pointer to a string:. If you want to avoid the ord "x" calls above, you can set the argtypes attribute, and the second argument will be converted from a single character Python bytes object into a C char:.
You can also use a callable Python object a function or a class for example as the restype attribute, if the foreign function returns an integer. The callable will be called with the integer the C function returns, and the result of this call will be used as the result of your function call.
This is useful to check for error return values and automatically raise an exception:. WinError is a function which will call Windows FormatMessage api to get the string representation of an error code, and returns an exception. WinError takes an optional error code parameter, if no one is used, it calls GetLastError to retrieve it.
Please note that a much more powerful error checking mechanism is available through the errcheck attribute; see the reference manual for details. Sometimes a C api function expects a pointer to a data type as parameter, probably to write into the corresponding location, or if the data is too large to be passed by value.
This is also known as passing parameters by reference. Structures and unions must derive from the Structure and Union base classes which are defined in the ctypes module.
Here is a simple example of a POINT structure, which contains two integers named x and y , and also shows how to initialize a structure in the constructor:. You can, however, build much more complicated structures. A structure can itself contain other structures by using a structure as a field type. Field descriptor s can be retrieved from the class , they are useful for debugging because they can provide useful information:. Unions and structures with bit-fields should always be passed to functions by pointer.
By default, Structure and Union fields are aligned in the same way the C compiler does it. This must be set to a positive integer and specifies the maximum alignment for the fields. This is what pragma pack n also does in MSVC. These classes cannot contain pointer fields. It is possible to create structures and unions containing bit fields. Here is an example of a somewhat artificial data type, a structure containing 4 POINTs among other stuff:. The above code print a series of 0 0 lines, because the array contents is initialized to zeros.
Pointer instances are created by calling the pointer function on a ctypes type:. Pointer instances have a contents attribute which returns the object to which the pointer points, the i object above:. Note that ctypes does not have OOR original object return , it constructs a new, equivalent object each time you retrieve an attribute:. Generally you only use this feature if you receive a pointer from a C function, and you know that the pointer actually points to an array instead of a single item.
Behind the scenes, the pointer function does more than simply create pointer instances, it has to create pointer types first. Calling the pointer type without an argument creates a NULL pointer. NULL pointers have a False boolean value:. Usually, ctypes does strict type checking. There are some exceptions to this rule, where ctypes accepts other objects.
For example, you can pass compatible array instances instead of pointer types. Sometimes you have instances of incompatible types.
In C, you can cast one type into another type. For these cases, the cast function is handy. The cast function can be used to cast a ctypes instance into a pointer to a different ctypes data type. It returns an instance of the second argument, which references the same memory block as the first argument:.
So, cast can be used to assign to the values field of Bar the structure:. Incomplete Types are structures, unions or arrays whose members are not yet specified.
In C, they are specified by forward declarations, which are defined later:. We create two instances of cell , and let them point to each other, and finally follow the pointer chain a few times:. These are sometimes called callback functions. First, you must create a class for the callback function.
The class knows the calling convention, the return type, and the number and types of arguments this function will receive. Both of these factory functions are called with the result type as first argument, and the callback functions expected argument types as the remaining arguments. The callback will then be called with two pointers to items, and it must return a negative integer if the first item is smaller than the second, a zero if they are equal, and a positive integer otherwise.
So our callback function receives pointers to integers, and must return an integer. First we create the type for the callback function:. This behavior is correct for most purposes, but it means that values stored with threading. Some shared libraries not only export functions, they also export variables. When a frozen module is imported, it is searched in this table. Third-party code could play tricks with this to provide a dynamically created collection of frozen modules.
So manipulating this pointer could even prove useful. To restrict the example size, we show only how this table can be read with ctypes :. The fact that standard Python has a frozen module and a frozen package indicated by the negative size member is not well known, it is only used for testing.
There are some edges in ctypes where you might expect something other than what actually happens. We certainly expected the last statement to print 3 4 1 2. What happened? Here are the steps of the rc. Note that temp0 and temp1 are objects still using the internal buffer of the rc object above. So executing rc. This, in turn, changes the contents of temp1. So, the last assignment rc. Why is it printing False?
Storing a Python object in the memory block does not store the object itself, instead the contents of the object is stored. Accessing the contents again constructs a new Python object each time! The resize function can be used to resize the memory buffer of an existing ctypes object. The function takes the object as first argument, and the requested size in bytes as the second argument.
The memory block cannot be made smaller than the natural memory block specified by the objects type, a ValueError is raised if this is tried:. This is nice and fine, but how would one access the additional elements contained in this array? Since the type still only knows about 4 elements, we get errors accessing other elements:. Another way to use variable-sized data types with ctypes is to use the dynamic nature of Python, and re- define the data type after the required size is already known, on a case by case basis.
The ctypes. Try to find a library and return a pathname. If no library can be found, returns None. It returns the filename of the library file. There are several ways to load shared libraries into the Python process. One way is to instantiate one of the following classes:.
Instances of this class represent loaded shared libraries. Functions in these libraries use the standard C calling convention, and are assumed to return int. This error message does not contain the name of the missing DLL because the Windows API does not return this information making this error hard to diagnose. To resolve this error and determine which DLL is not found, you need to find the list of dependent DLLs and determine which one is not found using Windows debugging and tracing tools.
Windows only: Instances of this class represent loaded shared libraries, functions in these libraries use the stdcall calling convention, and are assumed to return the windows specific HRESULT code. HRESULT values contain information specifying whether the function call failed or succeeded, together with additional error code.
If the return value signals a failure, an OSError is automatically raised. Windows only: Instances of this class represent loaded shared libraries, functions in these libraries use the stdcall calling convention, and are assumed to return int by default. The Python global interpreter lock is released before calling any function exported by these libraries, and reacquired afterwards.
Instances of this class behave like CDLL instances, except that the Python GIL is not released during the function call, and after the function execution the Python error flag is checked.
If the error flag is set, a Python exception is raised. All these classes can be instantiated by calling them with at least one argument, the pathname of the shared library. If you have an existing handle to an already loaded shared library, it can be passed as the handle named parameter, otherwise the underlying platforms dlopen or LoadLibrary function is used to load the library into the process, and to get a handle to it.
The mode parameter can be used to specify how the library is loaded. For details, consult the dlopen 3 manpage. On Windows, mode is ignored. The function ctypes. The winmode parameter is used on Windows to specify how the library is loaded since mode is ignored. When omitted, the default is to use the flags that result in the most secure DLL load to avoiding issues such as DLL hijacking.
Passing the full path to the DLL is the safest way to ensure the correct library and dependencies are loaded. Flag to use as mode parameter. On platforms where this flag is not available, it is defined as the integer zero.
The default mode which is used to load shared libraries. On OSX Instances of these classes have no public methods. Functions exported by the shared library can be accessed as attributes or by index. Please note that accessing the function through an attribute caches the result and therefore accessing it repeatedly returns the same object each time.
On the other hand, accessing it through an index returns a new object each time:. The following public attributes are available, their name starts with an underscore to not clash with exported function names:. Shared libraries can also be loaded by using one of the prefabricated objects, which are instances of the LibraryLoader class, either by calling the LoadLibrary method, or by retrieving the library as attribute of the loader instance.
Class which loads shared libraries. The result is cached, so repeated attribute accesses return the same library each time. Load a shared library into the process and return it. This method always returns a new instance of the library. Creates CDLL instances. Creates PyDLL instances. For accessing the C Python api directly, a ready-to-use Python shared library object is available:. 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.
Loading a library through any of these objects raises an auditing event ctypes. Accessing a function on a loaded library raises an auditing event ctypes. In cases when only the library handle is available rather than the object, accessing a function raises an auditing event ctypes. As explained in the previous section, foreign functions can be accessed as attributes of loaded shared libraries.
The function objects created in this way by default accept any number of arguments, accept any ctypes data instances as arguments, and return the default result type specified by the library loader. They are instances of a private class:. Instances of foreign functions are also C compatible data types; they represent C function pointers. This behavior can be customized by assigning to special attributes of the foreign function object. Assign a ctypes type to specify the result type of the foreign function.
Use None for void , a function not returning anything. It is possible to assign a callable Python object that is not a ctypes type, in this case the function is assumed to return a C int , and the callable will be called with this integer, allowing further processing or error checking. Using this is deprecated, for more flexible post processing or error checking use a ctypes data type as restype and assign a callable to the errcheck attribute.
Assign a tuple of ctypes types to specify the argument types that the function accepts. Functions using the stdcall calling convention can only be called with the same number of arguments as the length of this tuple; functions using the C calling convention accept additional, unspecified arguments as well.
This allows defining adapters that can adapt custom objects as function parameters. Assign a Python function or another callable to this attribute. The callable will be called with three or more arguments:. The object that this function returns will be returned from the foreign function call, but it can also check the result value and raise an exception if the foreign function call failed. This exception is raised when a foreign function call cannot convert one of the passed arguments.
On Windows, when a foreign function call raises a system exception for example, due to an access violation , it will be captured and replaced with a suitable Python exception. Further, an auditing event ctypes. Some ways to invoke foreign function calls may raise an auditing event ctypes. Foreign functions can also be created by instantiating function prototypes. Function prototypes are similar to function prototypes in C; they describe a function return type, argument types, calling convention without defining an implementation.
The factory functions must be called with the desired result type and the argument types of the function, and can be used as decorator factories, and as such, be applied to functions through the wrapper syntax. See Callback functions for examples.
The returned function prototype creates functions that use the standard C calling convention. The function will release the GIL during the call. The returned function prototype creates functions that use the Python calling convention. The function will not release the GIL during the call. Function prototypes created by these factory functions can be instantiated in different ways, depending on the type and number of the parameters in the call:.
Returns a foreign function exported by a shared library. The first item is the name of the exported function as string, or the ordinal of the exported function as small integer. The second item is the shared library instance. Returns a foreign function that will call a COM method. COM methods use a special calling convention: They require a pointer to the COM interface as first argument, in addition to those parameters that are specified in the argtypes tuple.
The optional paramflags parameter creates foreign function wrappers with much more functionality than the features described above. Each item in this tuple contains further information about a parameter, it must be a tuple containing one, two, or three items. The optional second item is the parameter name as string. If this is specified, the foreign function can be called with named parameters.
0コメント