Best way to call external function from another process memory?
rikki cattermole
rikki at cattermole.co.nz
Thu Nov 23 11:57:34 UTC 2017
On 23/11/2017 11:35 AM, Skuzzi wrote:
> Hi, I am new to D and I want to use it to create some tools that call
> certain functions from the process of a game, using an injected DLL
> written in D. I have reverse engineered the addresses and arguments of
> the function. Typically this kind of stuff is done with C++ and almost
> all the available resources online focus on C++. I was not able to find
> anything specific to this done in D.
>
> This is what a function prototype might look like in C++:
> typedef void (__stdcall* _function) (const char *text);
> _function function;
alias _function = extern(C) void function(const(char)* text);
_function myFunction;
> Which you would then call using the address of the function in memory:
> function = (_function)(ADDRESS_OF_FUNCTION);
> function("Some text");
void* ADDRESS_OF_FUNCTION = ...;
myFunction = cast(_function)ADDRESS_OF_FUNCTION;
myFunction(cast(const(char)*("Some text".ptr));
Literals have a \0 at the end so this is safe.
> I want to do this in D. I understand that D uses "extern (C)" and does
> away with specifying calling conventions. However, how does D know the
> calling convention required? What if it is a __thiscall or something
> else, will it always be handled properly by D, just be specifying
> "extern (C)"?
extern takes care of calling conventions and mangling for declarations
(which you are not using in the above).
See[0] point 3 regarding how this all works.
[0] https://dlang.org/spec/interfaceToC.html#calling_c_functions
More information about the Digitalmars-d-learn
mailing list