Passing a string back from C++/CLI to VBA

0

OK, I'm going slightly mad here. I have this C++/CLI declaration:

extern "C" __declspec(dllexport) int __stdcall Command(const char* commandName, const char* arguments, char* %result, int %resultLength) {
    System::String^ commandNameS = gcnew System::String(commandName);
    System::String^ argumentsS = gcnew System::String(arguments);
    System::String^ resultS = gcnew System::String(' ', 1000);
    int x = MainFunc::Command(commandNameS, argumentsS, resultS);
    resultLength = resultS->Length;

    char* str2 = (char*)(void*)System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(resultS);

    //result = str2;
    return x;
}

commandName and arguments go in correctly from VBA.

resultLength goes back correctly to VBA.

If I debug, str2 appears to hold the correct value (a hex value followed by a correct string in the debugger)

If I uncomment the //result = str2; line, I get a crash. Repeated debugging attempts get me to this error information:

*MSACCESS.EXE has triggered a breakpoint. occurred

ntdll.dll!_RtlReportCriticalFailure@12()    Unknown Symbols loaded.
oleaut32.dll!_SysFreeString@4() Unknown Symbols loaded.

A heap has been corrupted 0xC0000374*

So I suspect I need something to pin or hold the allocation of the string before passing it back to VBA

VBA6 declaration for Win32:

Private Declare Function Command Lib "External.Win32.dll" (ByVal CommandName As String, ByVal Argument As String, ByRef Result As String, ByRef ResultLength As Long) As Long

EDIT: Using *result = *str2; shows result equal to the first character in str2, but seems to still result in an empty string on the VBA side. No crash though.

c#
c++
vba
ms-access
asked on Stack Overflow Jan 25, 2018 by Roger Willcocks • edited Jul 3, 2020 by Martijn Pieters

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0