Hi everyone,

I wrote a dll which is export char* like;

extern "C" __declspec(dllexport) char* Test(void)
{
   char* cts = "hi";
   return cts;
}

and import the dll on vb.net like;

Declare Ansi Function Test Lib "[Path]" Alias "Test" () As String

and call like;

Private Sub Form_Load (...)
   Dim a As String = Nothing
   a = Test
   MsgBox(a)
End Sub

There isn't any problem. But I want to use CString and convert CString to char pointer and then export the pointer, like;

extern "C" __declspec(dllexport) char* Test(void)
{
   CString a(L"hi");
   char* cts = (char*)(LPCTSTR)a;
   return cts;
}

After the same VB.Net import and call functions, when the form is load (and Form_Load function called) then a error thrown as "AccessViolationError" (if I'm not wrong).

My question is how can I export char pointer (converted from CString variable) and use on VB.Net?

PS: Sorry for my English. By the way I'm using Visual Studio (VC++8)

Nick Evan commented: Good job on all the different code-tags! +12

Recommended Answers

All 2 Replies

I'd be really leery of returning a stack based temporary variable to a caller as you are doing.

Thanks everyone for useful tips. Well nobody answer but i found the solution; BSTR. Visual Basic 6 and .Net uses BSTR as "string".
If i want to export some string (as char pointer) on Visual C++ and use in Visual Basic (or .Net) simply write these codes;

BSTR [__stdcall] myfunc(void)
{

   char* cp_test = "foo";
   // I'm not sure is it right but
   CString cs_test(cp_test);
   return cs_test.AllocSysString();

}

This is the definition (*.def) file;

LIBRARY [dll_name]
EXPORTS
   myfunc @1

and import in VB.Net;

Imports System.Runtime.InteropServices

Public Class [class_name]

<DllImport("dll_path", CallingConvention:=CallingConvention.StdCall, CharSet:=CharSet.None)> _
Public Shared Function myfunc() As String
End Function
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.