locked
Passing char* and getting char* return from a C++ DLL to VB.NET application RRS feed

  • Question

  • I have a C++ DLL function with the following definition-

    char * scanImage(char * fileDir)
    {
    	string dir(fileDir);
    	string cvStr = cvScan(dir);
    	char * scanReturn;
    	scanReturn = (char*)CoTaskMemAlloc((cvStr.size() + 1) * sizeof(char));
    	strcpy(scanReturn, cvStr.c_str());
    	cout << "DLL Output: " << endl << scanReturn <<endl;
    	return scanReturn;
    }

    Header file of the DLL is-

    #pragma once
    #include <Windows.h>
    #include <string>
    using namespace std;
    
    #ifdef THEIA_OPENCV_DLL_EXPORTS
    #define THEIA_OPENCV_DLL_API __declspec(dllexport)
    #else
    #define THEIA_OPENCV_DLL_API __declspec(dllimport)
    #endif
    
    extern "C"  THEIA_OPENCV_DLL_API char * scanImage(char * fileDir);

    Now I want to call this scanImage function from a VB.NET Application.

    So far  I have been trying these-

    Trial 1:

    Imports System.Runtime.InteropServices

    Public Class Form1 Public Declare Function scanImage Lib "Theia_OpenCV_Dll.dll" (<MarshalAs(UnmanagedType.LPStr)> fileDir As String) As IntPtr Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim out As IntPtr = scanImage("files/stu2/2.bmp") Label1.Text = Marshal.PtrToStringAnsi(out) End Sub End Class

    This code changed the default text of label1 to blank. But displays nothing. On second click this terminates the program.

    Trial 2:

    Imports System.Runtime.InteropServices
    Public Class Form1
    
        Public Declare Function scanImage Lib "Theia_OpenCV_Dll.dll" (<MarshalAs(UnmanagedType.LPStr)> fileDir As String) As <MarshalAs(UnmanagedType.LPStr)> System.Text.StringBuilder
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim sb As System.Text.StringBuilder = scanImage("files/stu2/2.bmp")
            label1.text = sb.ToString
        End Sub
    
    End Class

    This gives me- Program_name has stopped working

    and the program terminates immediately.

    I am using VB.NET in Visual Studio 2017. Now how to solve this problem?


    Sayom Shakib




    Saturday, January 6, 2018 8:19 AM

Answers

  • Solved it:

    Public Class Form1
      
     <DllImport("F:\Work\OpenCV_Theia_Windows\Theia_OpenCV_Dll\x64\Debug\Theia_OpenCV_Dll.dll", CallingConvention:=CallingConvention.Cdecl)>
        Public Shared Function scanImage(ByVal fileDir As String) As System.IntPtr
        End Function
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim p As IntPtr = scanImage("files/stu2/2.bmp")
            Dim result As String = Marshal.PtrToStringAnsi(p)
            Label1.Text = result
        End Sub
    End Class

    nsssayom

    • Marked as answer by Sayom Shakib Saturday, January 6, 2018 8:38 AM
    Saturday, January 6, 2018 8:36 AM