EDIT 5
I have erased the previous post, since the code has been fully changed (hoping no rules violation).
I removed all previous references to problematic String variables.
Now the question:
For study purposes, I have made my first very simple Visual C++ DLL, and I want to use it in VB.Net.
In addition to the auto-generated files from Visual C++ (dllmain.cpc, pch.h, pch.cpp, to which I added my code.h) I have added two files to define my function:
code.h
#pragma once
#include "pch.h"
#ifndef ADD_CODE_H
#define ADD_CODE_H
//extern "C"
//{
__declspec(dllexport) int add_code(int lng);
//}
#endif
code.cpp
#include <iostream>
#include "pch.h"
#include "code.h"
int add_code(int lng) {
switch (lng) {
case 4:
return 1;
case 5:
return 2;
default:
return 9;
}
return 0;
}
No errors compiling the Visual C++ code. Tried both x86 and x64.
If I uncomment "Extern C"" by microsoft Dumper I get:
1 0 00001000 ?add_code@@YAHH@Z = ?add_code@@YAHH@Z (int __cdecl add_code(int))
If I comment it I obtain:
1 0 00001000 add_code = _add_code
From VB.NET, I try to call the DLL with this code:
vb.net
<DllImport("MyDll.dll", EntryPoint:="add_code@@YAHH@Z")> 'also "?add_code@@YAHH@Z"
'Also "CallingConvention: = CallingConvention.Cdecl
Public Shared Function add_code(ByVal lng As Integer) As Integer
End Function
And also:
<DllImport("MyDll.dll", EntryPoint:="_add_code")> ' Also "CallingConvention: = CallingConvention.Cdecl
Public Shared Function add_code(ByVal lng As Integer) As Integer 'Also "_add_code"
End Function
VB Main:
Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim foo As Integer = add_code(4) 'Also "_add_code"
End Sub
Tried both x86 (dll x86), x64 (dll x64) and Any Cpu (both dll x86 or x64).
I always get the error:
System.EntryPointNotFoundException: Could not find entry point with name 'add_code' in MyDll.dll
std::stringto/from managed code. Either use c++/cli in the middle, or for PInvoke you need to use a compatible string.extern "C"is incompatible withstdcallis confused, possibly it's trying to highlight the conflict with having astd::stringas an argument,stdcallitself most certainly is compatible withextern "C". But note thatstdcallis only meaningful in 32-bit code, there is only one calling convention in 64-bit.extern "C"isn't withstdcall, it's withstd::string.