Access violation when calling C DLL from D

AnoHito via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Nov 2 09:41:34 PST 2015


On Monday, 2 November 2015 at 15:56:20 UTC, Atila Neves wrote:
> Try this instead:
>
> https://github.com/jacob-carlborg/dstep
>
> It's been used to convert C Ruby declarations to D:
>
> https://github.com/jacob-carlborg/orbit/tree/master/ruby
>
> Atila

I might try it later, but I don't think the header conversion is 
the problem in this case. I tried to get some insight into what 
was happening by modifying the mrb_load_nstring function:

MRB_API mrb_value
mrb_load_nstring(mrb_state *mrb, const char *s, int len)
{
   FILE *f = fopen("output.txt", "w");
   fprintf(f, "mrb: %p, s: %p, len: %i\n", mrb, s, len);
   fclose(f);
   return mrb_load_nstring_cxt(mrb, s, len, NULL);
}

The output was:

mrb: 0052E818, s: 0000000E, len: 5

That was... odd. I tried to modify my extern statement a bit:

extern (C) mrb_value mrb_load_nstring(void *junk, mrb_state *mrb, 
const char *s, int len);

And ran the following code:

mrb = mrb_open();
mrb_value result =  mrb_load_nstring(cast(void *) 0, mrb, 
toStringz("String('test')"), 14);
Log.info(to!string(mrb_string_value_cstr(mrb, &result)));

This time the result was:

mrb: 0039E750, s: 0052E818, len: 14

Things actually got a little further now that the values were 
getting passed correctly(?) but another null pointer access 
violation got triggered later on in the code.

So something weird is definitely going on here. Is there 
something that needs to be done differently to handle the calling 
conventions here? I think all the functions in MRuby that I have 
attempted to call so far are regular cdecl functions.

Here is the definitions of MRB_API from the original header, in 
case it sheds any light on things:

#if defined(MRB_BUILD_AS_DLL)
#if defined(MRB_CORE) || defined(MRB_LIB)
# define MRB_API __declspec(dllexport)
#else
# define MRB_API __declspec(dllimport)
#endif
#else
# define MRB_API extern
#endif

Could the problem be because I used mingw to build the DLL, and 
Visual D to build my main project? It was more or less necessary, 
since Visual Studio's build tools couldn't handle the MRuby build 
scripts. I didn't think it should cause any problems, but maybe I 
was wrong.

Also, here is the command I used to generate the lib for the DLL:

implib /s mruby.lib mruby.dll

Is implib still the best tool for doing this? The only version I 
was able to find was very old, so maybe it is not generating the 
lib files correctly.


More information about the Digitalmars-d-learn mailing list