Problem Passing Struct to C

Mike Parker aldacron at gmail.com
Fri May 6 08:57:50 PDT 2011


On 5/6/2011 10:23 PM, Steven Schveighoffer wrote:
> On Fri, 06 May 2011 09:16:02 -0400, Jacob Carlborg <doob at me.com> wrote:
>
>> On 2011-05-06 11:56, Mike Parker wrote:
>>> Testing out a new binding I knocked up for a C library. One of the
>>> functions takes a struct by value. It looks somewhat like this:
>>>
>>> struct S {}
>>> struct Color
>>> {
>>> float r,g,b,a;
>>> }
>>>
>>> extern C void function(S* s, Color color, int x, int y, in char*)
>>> draw_text;
>>>
>>> Now, there is another function that adjusts color values when making a
>>> color. In C, it is sometimes used like so:
>>>
>>> draw_text(s, map_color(255, 0, 0, 0), 0, 0, "Blarg");
>>>
>>> When I'm calling draw_text like this on the D side, my text output is
>>> corrupt. I keep getting weird things like ^^P^, but in the appropriate
>>> color. It's consistent, no matter what string I pass, but is different
>>> for each color value. If I call draw_text like this:
>>>
>>> auto color = map_color(...);
>>> draw_text(s, color, 0, 0, "Blarg");
>>>
>>> It works as expected. Has anyone else seen this, or know of a
>>> workaround? I'm going to dig through bugzilla later on and see if it's
>>> been reported already, but I'm curious if anyone knows of the cause off
>>> hand.
>>
>> You need to convert the string into a C string;
>>
>> import std.string;
>> auto color = map_color(...);
>> draw_text(s, color, 0, 0, "Blarg".toStringz);
>>
>
> No, D implicitly casts string literals to zero-terminated const(char)*.
> That part is fine.
>

toStringz was actually the first thing I went for when I got the 
corrupted output, thinking that maybe literals were no longer null 
terminated.

I can't for the life of me figure out what's different about passing a 
local struct variable and one that's returned by value from a function 
call. The only thing I can think of is that the temp returned from the 
function is somehow corrupting the stack when it's pushed for the 
function call. But why? I'm hoping someone can shed some light on that 
aspect.


More information about the Digitalmars-d-learn mailing list