Pranit Kothari
Pranit Kothari

Reputation: 9841

Getting exception while using C++ dll in VB.Net

I have created unmanaged dll and used in VB.Net.

Both code snippiest is as follows.

VB.Net

Imports System.Text
Imports System.Runtime.InteropServices

Module Module1

    Sub Main()
        Dim c As cls = New cls()
        c.Start()
    End Sub

End Module

Public Class cls
    Declare Sub Only Lib "dllproj2.dll" Alias "Only" (b As StringBuilder)

    Public Sub Start()
        Dim s As StringBuilder = New StringBuilder(15)

        Only(s) '**Actual call to dll code **
        Dim s1 As String = s.ToString.ToLower
        Dim len As Integer = s.ToString.Length.ToString()
        Console.Write(s.ToString())
    End Sub

End Class

C++ dll

#include<stdio.h>
#include<stdlib.h>
#include<cstring>

extern "C"{
void Only(char *a)
{
    char arr[10];

    printf("Reached");
    sprintf(arr,"This %d",33);
    printf("\n%s\n",arr);
    memcpy(a,arr,10);

}
}

Now as soon as I access line Only(s) I get exception shown in image.

enter image description here

I am not able to understand cause of exception. Output of code is fine, but while running it using Visual Studio 2012 Express it is giving above error.

It is sample code, which we also used in production, I afraid it may cause problem in future.

Kindly suggest is there any way to get rid of exception.

Thanks.

Upvotes: 1

Views: 107

Answers (1)

Carlos Landeras
Carlos Landeras

Reputation: 11063

You have to declare bas: UnmanagedType.LPStr

Declare Sub Only Lib "dllproj2.dll" Alias "Only" (<InAttribute(), MarshalAs(UnmanagedType.LPStr)> b As StringBuilder)

Upvotes: 1

Related Questions