Calling D from C

Chris W. wendlec at tcd.ie
Mon Mar 12 08:34:23 PDT 2012


On Monday, 12 March 2012 at 15:17:32 UTC, Alex Rønne Petersen 
wrote:
> On 12-03-2012 16:09, Chris W. wrote:
>> On Monday, 12 March 2012 at 15:00:31 UTC, Steven Schveighoffer 
>> wrote:
>>> On Mon, 12 Mar 2012 10:53:09 -0400, Chris W. <wendlec at cd.ie> 
>>> wrote:
>>>
>>>> I have a problem when calling D functions from C. While I can
>>>> perform simple arithmetic operations (i.e. the calculation is
>>>> performed in D and returned to C), I experience problems when
>>>> trying to perform string/char operations or call functions 
>>>> from
>>>> the D standard library (e.g. writefln()). The usual error 
>>>> message
>>>> I get is either "Bus error" or "Segmentation fault". I 
>>>> haven't
>>>> been able to find the reason for this. The programs compile 
>>>> and
>>>> link, however, when run, they terminate with "Bus error" 
>>>> whenever
>>>> a D function is performed within the D code, e.g. something 
>>>> like
>>>> char[] s2 = s.dup; (s is a char* passed from C). Any hint or 
>>>> help
>>>> would be appreciated.
>>>>
>>>> I am using Mac OS X, 10.6.7
>>>
>>> If C is running your application startup, you must initialize 
>>> D's
>>> runtime from your C main routine.
>>>
>>> -Steve
>>
>> Yes, I am using extern (C) and in my C main function I call
>>
>> gc_init();
>> thread_attachThis();
>>
>> This works fine for primitive types such as int + int 
>> calculations. But
>> anything more sophisticated renders a Bus error. I am sure it 
>> is just
>> some little detail I have forgotten.
>
> Don't forget to call this: 
> https://github.com/D-Programming-Language/druntime/blob/master/src/core/runtime.d#L33
>
> Documented here: 
> https://github.com/D-Programming-Language/druntime/blob/master/src/core/runtime.d#L101

Thanks a million, calling rt_init(); in my C code did the trick. 
Now I can perform string operations etc. I knew it was just a 
tiny little detail.


More information about the Digitalmars-d mailing list