Access violation when calling C DLL from D

Nicholas Wilson via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Nov 2 05:20:21 PST 2015


On Monday, 2 November 2015 at 01:02:45 UTC, AnoHito wrote:
> Hi, I am trying to write a simple interface to the MRuby Ruby 
> interpreter so I can use ruby scripts in my D program. I was 
> able to get MRuby compiled as a DLL without too much 
> difficulty, but the headers are very long and complicated, and 
> porting them entirely to D would be a huge project in and of 
> itself. I am trying to get by with only what I need, so here is 
> what I have so far:
>
> module script.mruby;
>
> alias mrb_bool = bool;
> alias mrb_int = int;
> alias mrb_float = double;
> alias mrb_sym = uint;
>
> alias mrb_aspec = uint;
>
> struct mrb_value
> {
>
> }
> struct RObject
> {
>
> }
>
> struct RClass
> {
>
> }
>
> struct mrb_value
> {
>
> }
>
> struct mrb_state
> {
>
> }
>
> extern(C) char *mrb_string_value_cstr(mrb_state *mrb, mrb_value 
> *ptr);
>
> extern (C) mrb_value mrb_load_string(mrb_state *mrb, const char 
> *s);
> extern (C) mrb_value mrb_load_nstring(mrb_state *mrb, const 
> char *s, int len);
>
> extern (C) mrb_state *mrb_open();
> extern (C) void mrb_close(mrb_state *mrb);
>
In D the unary * is left associative NOT right. i.e. write int* 
a,b,c; // a,b and c are all int* NOT  int*, int,int as would be 
the case in C
because you are not allowed to change the type during the 
declaration.

> In theory, this should be enough to test that MRuby is working, 
> so I tried to run the following code:
>
> mrb = mrb_open();
> mrb_value result = mrb_load_string(mrb, 
> toStringz("String('test')"));

string literals are automatically null terminated, no need to 
`toStringz`. if it was not a literal the you would have to.

> Log.info(to!string(mrb_string_value_cstr(mrb, &result)));
>
> But the result was:
>
> object.Error@(0): Access Violation
>

(0) suggests a null pointer

> I wasn't able to get the Visual D debugger to trace into the 
> code, but after some investigation, I figured out that the 
> error was occurring in the strlen runtime function. I don't 
> think I did anything wrong with the way I passed a string into 
> the mrb_load_string function, so I am kind of at a loss as to 
> what the problem might be.
and the only operation here likely to call strlen is to!string 
from a char* (since D strings know their length)

perhaps you should inspect the value returned from 
mrb_string_value_cstr

few possible places to look
         alignment - are the types declared in c declared with an 
alignment?
         check the values of mob and result

Also take a Look at DStep on github for auto translation of C


More information about the Digitalmars-d-learn mailing list