Calling D from C

Alex Rønne Petersen xtzgzorex at gmail.com
Mon Mar 12 08:39:14 PDT 2012


On 12-03-2012 16:36, Steven Schveighoffer wrote:
> On Mon, 12 Mar 2012 11:17:31 -0400, Alex Rønne Petersen
> <xtzgzorex at gmail.com> 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
>>
>
> More appropriate:
>
> http://dlang.org/phobos/core_runtime.html#initialize

But that's effectively an extern (D) function. That's why I linked to 
rt_init.

>
> And actually, I think this should do everything necessary. No need to
> call gc_init and thread_attachThis().
>
> -Steve


-- 
- Alex


More information about the Digitalmars-d mailing list