Using FFI to write a std::string to a buffer passed in from D

Troy tmj9001 at gmail.com
Sun Jul 21 17:25:46 UTC 2024


On Sunday, 21 July 2024 at 15:31:47 UTC, Johan wrote:
> On Sunday, 21 July 2024 at 13:35:46 UTC, Troy wrote:
>>
>> void create(void* b) {
>> 	std::string s = "engineer again";
>> 	*(std::string*)(b) = s;// Segfault here
>> }
>
> You have to construct an empty string object first in location 
> `b` (emplacement new). Then you can assign to it as you do.
> The `=` calls `operator=` which assumes that both operands (`b` 
> and `s`) are both fully constructed and valid `std::string` 
> objects. Without emplacement new, `b` is not a valid 
> `std::string` object (random byte buffer returned by `malloc`).
>
> Hope that works,
>   Johan

Using placement new like you suggested seems to have solved my 
issue perfectly.  I would never have never thought of that on my 
own.  Thanks for the suggestion!


More information about the Digitalmars-d-learn mailing list