473,563 Members | 2,697 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Python loading library containing embedded python...


I have a dll/so which embeds python. I can verify it works by
compiling it as an executable and adding an appropriate main.

I tried to write unit tests for this library with ctypes and a simple
python script. Access violations and other strange things result. I
suspect this is because I am basically embedding python in python at
this point.

How can I make my dll/so with embedded python support use via ctypes?

If Py_NewInterpret er is the answer, why does it hang indefinitely?

The dll/so must support use in processes which might contain other
instances of Python. I can not change that requirement. Running via
ctypes is an easy test of this capability (or much of it I suspect).
Jan 28 '06 #1
8 2416
Brennus wrote:
I have a dll/so which embeds python. I can verify it works by
compiling it as an executable and adding an appropriate main.
Please explain in more detail how you did the embedding. Did you
statically link the Python interpreter into your dll/so, or did
you use a shared one?
How can I make my dll/so with embedded python support use via ctypes?
Whether you can do this at all depends on the fine details of
embedding: e.g. what operating system, how precisely did you do
the embedding, and so on.

For example, on many Unix systems, you might end up with two definitions
of all the Python symbols, at which point it depends on the precise
linker command line options to determine what precisely happens
(e.g. which of the definition of the symbol is used in what place).
The dll/so must support use in processes which might contain other
instances of Python. I can not change that requirement. Running via
ctypes is an easy test of this capability (or much of it I suspect).


Then your best bet is to *really* embed Python. I.e. link all symbols
statically, preferably renaming them (if possible), and make sure that
the resulting dll does neither reference nor expose any Python symbols.
Given the different linkers on different systems, this is very tricky
to implement.

Regards,
Martin
Jan 29 '06 #2
Martin v. Löwis wrote:
Brennus wrote:
I have a dll/so which embeds python. I can verify it works by
compiling it as an executable and adding an appropriate main.


Please explain in more detail how you did the embedding. Did you
statically link the Python interpreter into your dll/so, or did
you use a shared one?


I compiled pythoncore.lib. I statically link this to my dll
and define Py_BUILD_CORE before including Python.h.

The only difference I can see with doing this vs linking the
python dll dynamically is that Py_IsInitialize d returns true
when using the dll. This makes sense, but little else does.
How can I make my dll/so with embedded python support use via ctypes?


Whether you can do this at all depends on the fine details of
embedding: e.g. what operating system, how precisely did you do
the embedding, and so on.

For example, on many Unix systems, you might end up with two definitions
of all the Python symbols, at which point it depends on the precise
linker command line options to determine what precisely happens
(e.g. which of the definition of the symbol is used in what place).
The dll/so must support use in processes which might contain other
instances of Python. I can not change that requirement. Running via
ctypes is an easy test of this capability (or much of it I suspect).


Then your best bet is to *really* embed Python. I.e. link all symbols
statically, preferably renaming them (if possible), and make sure that
the resulting dll does neither reference nor expose any Python symbols.
Given the different linkers on different systems, this is very tricky
to implement.


For now, I am testing this in Windows with Visual Studio.

I will look into renaming the symbols, but I am not sure
I understand why this is necessary. Surely two unrelated
DLLs can exist in a process with the same function names?
If not, I am surprised this problem hasn't been seen or
even exploited by plugin competitors more often.

Most of the time Py_Initialize and Py_IsInitialize d works.
High level tests with PyRun_SimpleStr ing("") crash in any
DLL I use from ctypes, while working fine as an executable.
Jan 29 '06 #3
I have a dll/so which embeds python. I can verify it works by
compiling it as an executable and adding an appropriate main.

I tried to write unit tests for this library with ctypes and a simple
python script. Access violations and other strange things result. I
suspect this is because I am basically embedding python in python at
this point.

How can I make my dll/so with embedded python support use via ctypes?

If Py_NewInterpret er is the answer, why does it hang indefinitely?

The dll/so must support use in processes which might contain other
instances of Python. I can not change that requirement. Running via
ctypes is an easy test of this capability (or much of it I suspect).


I have solved my problem, or at least part of it by downgrading
to Visual Studio 2003. For whatever reason, the same steps applied
to Visual Studio 2005 result in massive problems.

Even the python.exe compiled by VS 2005 throws A/Vs on startup.

Does Python have to use Visual Studio? I have, of course, seen
the MinGW Python patches and tutorials, but I am told I should
not use anything but what Python was compiled with.

Additionally, since a Python compiled with even VS 2005 is majorly
broken, I am wary of using MinGW unless it is officially supported.

Are there plans to move away from VS? It's horrible imho. I only
upgraded from VS 6 at the recommendation I should use the same
compiler used to compile the latest Python. I asked why, citing my
own knowledge of struct alignment concerns between compilers, but
was vaguely told it was very bad, and that FILE structs can differ.
Jan 30 '06 #4
Brennus <xo*****@gmail. com> wrote:
...
I have solved my problem, or at least part of it by downgrading
to Visual Studio 2003. For whatever reason, the same steps applied
to Visual Studio 2005 result in massive problems.

Even the python.exe compiled by VS 2005 throws A/Vs on startup.
I believe the python core developers who do develop on Windows have not
even tried VS 2005 and have no intention of so doing for the foreseeable
future. Unfortunate -- as a python core developer myself, while I
mostly use MacOSX, and secondarily Linux, I'd be happy to lend a hand
occasionally with Windows *IF* I could use VS 2005, which I can get for
free, rather than any product I'd have to pay for.

But, it's not up to me: I use Windows only when I really truly have to
(e.g., to check that things work there, too, before publishing articles
or books) -- I WON'T commit to spending substantial time and effort on
Windows as long as I can use GOOD systems like the Mac or Linux (I used
to make a living as a Windows guru, see <http://www.aleax.it/TutWin32/>
for a trace of that, and exactly because of that I know use Windows as
rarely as I can get away with!-).

The choice of what Windows environment is best is obviously up to those
python core developers who DO use Windows day-in, day-out (such as Tim
Peters -- there may be others, but I can't really think of any offhand).
Are there plans to move away from VS? It's horrible imho. I only


I don't know of any such plans, sadly. You may want to take up the
subject on python-dev: few core developers routinely follow this list
(or newsgroup, whatever;-). If you volunteer to port the development
environment for Windows to X, and can show that the performance with
whatever compiler X offers is better than VS's, you may stand a chance.
Good luck... you'll need quite a bit;-).
Alex
Jan 30 '06 #5
Brennus wrote:
I have solved my problem, or at least part of it by downgrading
to Visual Studio 2003. For whatever reason, the same steps applied
to Visual Studio 2005 result in massive problems.

Even the python.exe compiled by VS 2005 throws A/Vs on startup.

Does Python have to use Visual Studio?
Is this the debug build, by any chance? Microsoft broke support
for ISO C in VS2005. The Python trunk has a work-around for that
breakage.
I have, of course, seen
the MinGW Python patches and tutorials, but I am told I should
not use anything but what Python was compiled with.
More likely, you managed to mix msvcrt versions somehow. You
need to inspect your resulting DLL in depends.exe; please report
what it depends on.

Also notice that you cannot use extension DLLs in your embedded
Python: all extension DLLs depend on python2x.dll, so importing
one of them leads to multiple copies of the Python code in your
interpreter.
Are there plans to move away from VS?
Well, VS is the the "platform compiler", so no. Of course, if
you wanted that to happen, you could write a PEP, and explain
what alternative compiler (plus alternative build procedure)
should be used.
It's horrible imho. I only
upgraded from VS 6 at the recommendation I should use the same
compiler used to compile the latest Python. I asked why, citing my
own knowledge of struct alignment concerns between compilers, but
was vaguely told it was very bad, and that FILE structs can differ.


The problem really is with multiple copies of msvcrt. The struct
alignment in FILE structs is the same across all releases of
VC, yet having two copies of msvcrt in memory still might lead
to crashes.

The problem is that each msvcrt has its own FILE table, so
each one has its own stdout, for example. Now, for ages,
Microsoft also supports multi-threading in msvcrt, so there
was a need to extend struct FILE. They did so by introducing
struct FILEX, with an additional lock field. For
compatibility, they couldn't change the layout of the existing
array of FILE, so for the first 20 FILE values, the
lock is stored elsewhere (not in the __iob array, but in a
separate _locktable).

Now, when a file gets locked, msvcrt checks whether its pointer
is between __iob and __iob+20; if it is, it assumes it is
its own FILE, and looks for the lock in _locktable, else it
assumes it is FILEX, and looks for the lock in the struct itself.
If the FILE* really points into __iob of a different msvcrt,
that crashes.

Similar issues exist for malloc/free: you must not free a
pointer allocated by the malloc of a different msvcrt. Each
mscvrt has its own heap, and releasing memory to the wrong
heap might cause memory leaks.

Regards,
Martin
Jan 30 '06 #6
Brennus wrote:
I compiled pythoncore.lib. I statically link this to my dll
and define Py_BUILD_CORE before including Python.h.
Can you please elaborate? How did you do this? How do you know
pythoncore.lib is a static library? What msvcrt is it linked
with (use depends.exe to find out)?
The only difference I can see with doing this vs linking the
python dll dynamically is that Py_IsInitialize d returns true
when using the dll. This makes sense, but little else does.
You should explicitly call Py_Initialize in your embedded
application. Py_Initialize should return false before you
do so, and true afterwards. If that is not the case (e.g.
if Py_Initialize returns true even though you haven't called
Py_Initialize), something is wrong.
For now, I am testing this in Windows with Visual Studio.

I will look into renaming the symbols, but I am not sure
I understand why this is necessary. Surely two unrelated
DLLs can exist in a process with the same function names?
On Windows, yes. Not on Unix, atleast not in general.
If not, I am surprised this problem hasn't been seen or
even exploited by plugin competitors more often.


For plugins, there is a real problem on Unix, with several
strategies to solve it available. Avoiding naming conflicts
in the first place is the only one that really works,
independently of the plugin host.

Regards,
Martin
Jan 30 '06 #7
Alex Martelli wrote:
I believe the python core developers who do develop on Windows have not
even tried VS 2005 and have no intention of so doing for the foreseeable
future.
That is not true. I have already tried it. Many others did, too, and
found that Microsoft managed to break ISO C compliance in VS 2005
(in order to make it "safe").
The Python trunk has a work-around for that problem.
Unfortunate -- as a python core developer myself, while I
mostly use MacOSX, and secondarily Linux, I'd be happy to lend a hand
occasionally with Windows *IF* I could use VS 2005, which I can get for
free, rather than any product I'd have to pay for.
You can use VS2005 just fine. You have to convert the project files,
and then you are done.
The choice of what Windows environment is best is obviously up to those
python core developers who DO use Windows day-in, day-out
Not really. Users formulate all kinds of demands, and we listen to them.
Name an arbitrary Windows compiler, and somebody will have proposed to
use that as the compiler for the official Windows binaries. Mention that
you are going to stick with the compiler you use, and somebody will
complain. Mention that you are going to change compilers, and somebody
will complain. You can't win.
I don't know of any such plans, sadly. You may want to take up the
subject on python-dev: few core developers routinely follow this list
(or newsgroup, whatever;-). If you volunteer to port the development
environment for Windows to X, and can show that the performance with
whatever compiler X offers is better than VS's, you may stand a chance.
Good luck... you'll need quite a bit;-).


I personally don't care much about the performance of the compiler.
For my own development, I care about the tool integration, in particular
about the debugger (I like the MSVC debugger quite a lot). For the
Python project, I care about the compilers people want to use to
build extensions with.

For example, you can't really build COM-based extensions with cygwin,
so if the official compiler would be cygwin, somebody would have to
find out how to build PythonWin (in addition, PythonWin also has
a strong dependency on MSVCRT).

Regards,
Martin
Jan 30 '06 #8
"Martin v. Löwis" <ma****@v.loewi s.de> wrote:
Brennus wrote:
I have solved my problem, or at least part of it by downgrading
to Visual Studio 2003. For whatever reason, the same steps applied
to Visual Studio 2005 result in massive problems.

Even the python.exe compiled by VS 2005 throws A/Vs on startup.

Does Python have to use Visual Studio?
Is this the debug build, by any chance? Microsoft broke support
for ISO C in VS2005. The Python trunk has a work-around for that
breakage.


Good to hear, for my sanity at least.

I was actually thinking Microsoft was losing or breaking C on
purpose after using VS2005, and even VS2003 to some degree.

I think it's some sort of tactic. That's another reason I don't
want to continue using VS for Python.
I have, of course, seen
the MinGW Python patches and tutorials, but I am told I should
not use anything but what Python was compiled with.


More likely, you managed to mix msvcrt versions somehow. You
need to inspect your resulting DLL in depends.exe; please report
what it depends on.


I can't manage to compile anything with VS when Code Generation
is not set to the same type across projects. I guess I will try
the VS 2005 route again with this and the VS2005 patches in mind.

I am setting Code Generation the same across projects so I figured
that meant I was using the same C runtimes.
Also notice that you cannot use extension DLLs in your embedded
Python: all extension DLLs depend on python2x.dll, so importing
one of them leads to multiple copies of the Python code in your
interpreter.
Are there plans to move away from VS?


Well, VS is the the "platform compiler", so no. Of course, if
you wanted that to happen, you could write a PEP, and explain
what alternative compiler (plus alternative build procedure)
should be used.


I imagine MinGW's build process would be much easier.
I *think* I have to keep two Python trees just to *easily*
compile static and dynamic import lib files from Python VS.

Otherwise, it is quite easy to overwrite a 3 meg static
pythoncore.lib with the 200k dynamic/import version.
Jan 30 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
2141
by: quadric | last post by:
Hi, I have an application that has an embedded/extended Python interpreter. I need to add database capabilities and for reasons to lengthy to explain in this email, also require an embedded database server. I have tentatively chosen mySQL 4.0 due to the apparent ease of embedding, along with it having all the necessary database...
2
4193
by: JM | last post by:
Hello everyone, Does anybody know about, have documentation on, or have any code samples on how to access class members from a python class in C++. Say I have a simple python script: --------------------------- class Animal: NumLegs = 5
0
1206
by: Chris Esther | last post by:
I discovered what appears to be a copy of Python 2.1 included/embedded? with the video editing system Avid Adrenalin Media Composer (Win XP). In the program directory there is python21.dll and a directory containing the standard library. As I'm in the middle of an exercise to see if I can automate some non-creative tasks in the creation of...
13
2782
by: Alexander May | last post by:
Hi, I love Python! I've been using it for a couple of years now and have found it to be a highly productive language. I evangelize it to my developer friends and am probably responsible for the sale of at least 10 Alex Martelli books. I am now in the fortunate position of being able to use Python for a large project, and as such I have a...
2
432
by: Anand K Rayudu | last post by:
Hi all, I have embedded python and want to execute python scripts from my application. I need to call the execution of python repeatedly, and some times same script again & again. I am facing some problems , especially if i try to execute the same script again. Some times in loading my module. Even it looks like for loops are not...
2
2327
by: Miki Tebeka | last post by:
Hello All, I have a funny problem: An embedded python application is working fine on a "clean" computer. When it runs on a computer with python installed (the very same computer used to produce the application) it has a import error: ---------- can't import SACD module (sacd.py) Error in sys.exitfunc:
0
1284
by: proteusguy | last post by:
I've got a large C++ application that we're adding web integration to, XMLRPC and HTTP GET/POST stuff. I'm jumping at the chance to use embedded python to handle this aspect of the application as its so much quicker to handle all the SSL, XML, and HTTP stuff with python and, when the web service we integrate with changes I want to be able to...
0
1552
by: vishnu | last post by:
Hello All, I have embedded python 2.5 in to my C application. As we need the python scripts to run in multi threaded environment I have used Py_NewInterpreter() and Py_EndInterpreter each time I execute a run script function. The code is as follows: RunScript(char *pScriptName,char *pFuncName,...) { PyEval_AcquireLock()
1
3554
by: mmacrobert | last post by:
Hi Everyone, I've created a 'C' dll that is accessed via ctypes library containing a bunch of functions. I've successfully been able to use the functions. However, I would like to throw python exceptions from some of them. I throw them using: ::PyErr_SetString(::PyExc_RuntimeError, theErrorString); I crash the console when this function...
0
7580
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7882
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7634
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7945
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6244
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5208
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3634
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3618
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
916
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.