Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call a DLL from a scripting language?

Tags:

python

perl

dll

I have a third-party product, a terminal emulator, which provides a DLL that can be linked to a C program to basically automate the driving of this product (send keystrokes, detect what's on the screen and so forth).

I want to drive it from a scripting language (I'm comfortable with Python and slightly less so with Perl) so that we don't have to compile and send out executables to our customers whenever there's a problem found.

We also want the customers to be able to write their own scripts using ours as baselines and they won't entertain the idea of writing and compiling C code.

What's a good way of getting Python/Perl to interface to a Windows DLL. My first thought was to write a server program and have a Python script communicate with it via TCP but there's got to be an easier solution.

like image 381
paxdiablo Avatar asked Oct 27 '08 03:10

paxdiablo


5 Answers

One way to call C libraries from Python is to use ctypes:

>>> from ctypes import *
>>> windll.user32.MessageBoxA(None, "Hello world", "ctypes", 0);
like image 104
albertb Avatar answered Oct 29 '22 03:10

albertb


In Perl, Win32::API is an easy way to some interfacing to DLLs. There is also Inline::C, if you have access to a compiler and the windows headers.

Perl XSUBs can also create an interface between Perl and C.

like image 21
Axeman Avatar answered Oct 29 '22 04:10

Axeman


In Perl, P5NCI will also do that, at least in some cases. But it seems to me that anything you use that directly manages interfacing with the dll is going to be user-unfriendly, and if you are going to have a user (scriptor?) friendly wrapper, it might as well be an XS module.

I guess I don't see a meaningful distinction between "compile and send out executables" and "compile and send out scripts".

like image 22
ysth Avatar answered Oct 29 '22 04:10

ysth


For Python, you could compile an extension which links to the DLL, so that in Python you could just import it like a normal module. You could do this by hand, by using a library like Boost.Python, or by using a tool such as SWIG (which also supports Perl and other scripting languages) to generate a wrapper automatically.

like image 21
monopocalypse Avatar answered Oct 29 '22 03:10

monopocalypse


The Python Py_InitModule API function allows you to create a module from c/c++ functions which can then be call from Python.

It takes about a dozen or so lines of c/c++ code to achieve but it is pretty easy code to write:

https://python.readthedocs.org/en/v2.7.2/extending/extending.html#the-module-s-method-table-and-initialization-function

The Zeus editor that I wrote, uses this appoach to allow Zeus macros to be written in Python and it works very well.

like image 32
jussij Avatar answered Oct 29 '22 02:10

jussij