access violation With dll?
jklp via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Jul 16 10:22:49 PDT 2015
On Thursday, 16 July 2015 at 17:04:09 UTC, Taylor Hillegeist
wrote:
> Beleive it or not the code below does work. However I get an
> access violation after every run? any Ideas why?
>
>
> +++++++++++++++++++++++++Code to Run DLL
> function+++++++++++++++++++++++++++
>
> import core.runtime;
> import std.stdio;
> import core.memory;
> import std.c.windows.windows;
>
> int main()
> {
> HMODULE h;
> FARPROC fp;
>
> printf("Start Dynamic Link...\n");
> h = cast(HMODULE) Runtime.loadLibrary("SharedLib.dll");
>
> void function(ref char[], int) Testf
> = cast(void function(ref char[], int))
> GetProcAddress(h, "Test"); //Function Says HELLO WORLD
>
> char[] STUFF;
> STUFF.length = 5000;
> Testf( STUFF , STUFF.length);
>
> printf("%s\n", (&STUFF)); //PRINTS HELLO WORLD
>
> Runtime.unloadLibrary(h);
>
> printf("End...\n");
> return 0;
> }
> ++++++++++++++++++++++++++++++END
> CODE+++++++++++++++++++++++++++
> the function header has this line:
>
> void __cdecl Test(char MyOutput[], int32_t len);
>
> and i get this Error:
> object.Error@(0): Access Violation
> ----------------
> 0x77206568
> 0x646C726F
> 0x00405A2C in int object.ModuleInfo.opApply(scope int
> delegate(object.ModuleInfo*))
> 0x0040222C in main
> 0x00414949 in mainCRTStartup
> 0x7678337A in BaseThreadInitThunk
> 0x770592E2 in RtlInitializeExceptionChain
> 0x770592B5 in RtlInitializeExceptionChain
>
> To be honest I was surprised this worked, since i am fairly
> unfamiliar to linking to dlls.
Your proto is wrong. Your forgot the FFI convention (__cdecl =
extern(C)).
Try this instead:
---
extern(C)
alias Proto = void function(char*, int);
Proto func = cast(Proto) GetProcAddress(h, "Test");
if (func)
{
char[] STUFF;
STUFF.length = 5000;
func (STUFF.ptr , STUFF.length);
// prints etc...
}
----
More information about the Digitalmars-d-learn
mailing list