0

VB.NET

<DllImport("MyCtesting.dll")> _
Private Shared Sub test(ByRef _IMSS_TEXT As String)
End Sub


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    test(Label1.Text)
End Sub

C++

using boost::lexical_cast;
using boost::bad_lexical_cast;


extern "C"  __declspec(dllexport) void test(std::string &name)
{
    for (int i=0l;i<10;i++)
    {
        name = lexical_cast<string>(i);
    }
}

Why this is throwing error

Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

Thank in advance.

Rowland Shaw
  • 37,700
  • 14
  • 97
  • 166
al.pertro
  • 55
  • 5
  • 1
    My C++ is rusty (early 90s, pre-templates), and I've never used Boost, but shouldn't you be initializing lexical_cast with something before using it? – MetalMikester Feb 17 '14 at 19:57
  • 2
    I'm pretty sure that without some kind of marshaling, you can't send a System.String to a std::string. see: [Custom Marshaler for PInvoke with std::string](http://stackoverflow.com/questions/17099611/custom-marshaler-for-pinvoke-with-stdstring) – crashmstr Feb 17 '14 at 19:58
  • No it's not that important i think – al.pertro Feb 17 '14 at 19:59
  • I could send a string ,,, But just when you need to update string like for or loop in some file and update that's throw an error – al.pertro Feb 17 '14 at 20:01
  • I think crashmstr is on the right path. – MetalMikester Feb 17 '14 at 20:01
  • 1
    please read [the MSDN documentation on marshaling strings](http://msdn.microsoft.com/en-us/library/s9ts558h%28v=vs.110%29.aspx) – Mgetz Feb 17 '14 at 20:02
  • OK but i have Q which one is = to std:: string UnmanagedType.AnsiBStr UnmanagedType.BStr UnmanagedType.LPStr UnmanagedType.LPTStr (default) UnmanagedType.LPWStr UnmanagedType.TBStr VBByRefStr – al.pertro Feb 17 '14 at 20:06
  • 1
    This is not possible. There's no C string type that maps to a C++ std::string. This kind of interop is difficult even in C++, it requires building *both* with the exact same compiler using the exact same settings with the exact same runtime library version. You will need to use C++/CLI to write a wrapper and probably recompile the DLL. – Hans Passant Feb 17 '14 at 20:43
  • 1
    @al.pertro none of those. You can work with c-style strings, COM BSTR string, etc. to pass data back and forth. If you need to do `std::string` operations, you will need to do that with a local variable (or convert to use C++/CLI and System::String^). – crashmstr Feb 17 '14 at 20:44

0 Answers0