I have a problem passing strings to dll. I wrote this simple dll in visual studio 2008 for unity :
but when I want to call it through unity, I have two problems : 1. It returns 0 regardless of what string I pass into it. 2. At second call it crashes.
and this is my unity code:
Thanks in advance.
asked Sep 21 '10 at 08:15 AM
This is not a Unity-specific concern, but rather more general to mono and system interop. You're having trouble with marshaling between managed and unmanaged code. See the Unity docs on plugins and more precisely the linked mono documentation in that page.
You should beware of function name mangling because the interop was written assuming a C ABI. If mono can't find your function in the dll, it's not going to work. To resolve this, either wrap your C++ code in an
The data structure of a .net language string is a fair bit different from a C++ STL string. The way they are marshaled can be handled a number of ways, but essentially it's going to marshal as some form of char array, be it a LPCSTR or wchar* or something like that, not as an STL string (since the interop is assuming a C ABI and that didn't provide for the STL string). Please read this section of the same mono documentation on marshaling strings.
As for why you're crashing, odds are it has to do with some of the above, but I can't be sure.
Also, you don't need to include iostream or string.h if you aren't using them.
answered Sep 21 '10 at 03:21 PM
I looked through the Mono docs and the plugin docs and didn't find a good answer for this, and wanted to give some more info. I found there are a few caveats to passing a string to a C plugin.
Here is an example function in C:
And corresponding MonoBehavior code: