Re: Special use case for ctypes

eryk sun <[email protected]> Fri, 5 May 2017 14:52:17 +0000
Newsgroups gmane.comp.python.ctypes
Message-ID <CACL+1asmG2L=Q6O4d+VawaE8c3mseQfOzt-pXDc9KHCuibSiiA@mail.gmail.com>
On Fri, May 5, 2017 at 1:52 PM, Zak Smolen <[email protected]> wrote:
> So my thought behind this is that it must be possible... somehow, because of
> debuggers. You can attach a debugger to an existing process and see it's
> memory and such. I don't need simultaneous access from both the C# wrapper
> and the python at the same time. I can have the C# not touch the C while the
> python is running. It looks like debuggers do things with signals and such.

Reading the memory of a process like a debugger is not much of a
programming interface. ReadProcessMemory [1] requires a process handle
with VM read access (e.g. your Python script would need a handle for
the C# process). It's implemented by having the memory manager attach
to the process, map the target address range into kernel space, and
then attach to your process and copy that data to your buffer.
WriteProcessMemory [2] requires a handle with VM write and operation
access, and it's implemented in the opposite direction: map your
buffer to kernel space and then attach to the target process and write
the data at the target address. Considering these two address spaces
are unrelated, you'd need some IPC scheme to send the base address to
the process that wants to read from or write to memory in your
process.

If you want a section of shared memory, the DLL has to be designed
around it from the start. As far as the code in the DLL is concerned
it's just reading from and writing to a global variable at an address
in the current process. But under the hood the pages (typically 4 KiB
each) are shared with every process that loads the DLL, so they all
access the same data.

The alternative is to embed CPython in your .NET application. If
Python for .NET is hosted out of process, then yes it will be a
separate DLL instance. But you could still investigate directly
loading pythonXX.dll in your process to run the interpreter and have
ctypes (for whatever reason you need to do this in Python instead of
C#) access the DLL in your current process.

[1]: https://msdn.microsoft.com/en-us/library/ms680553
[2]: https://msdn.microsoft.com/en-us/library/ms681674

------------------------------------------------------------------------------
Check out the vibrant tech community on one of the world's most
engaging tech sites, Slashdot.org! http://sdm.link/slashdot