Calling C++ function from Excel and VBA using DLL created in C++

后端 未结 4 2039
情话喂你
情话喂你 2020-12-16 21:14

I created a DLL containing a function named \"koduj\". Calling this function by using it inside an Excel worksheet cell returns the desired result. Calling \"koduj\" from VB

相关标签:
4条回答
  • 2020-12-16 21:20

    Not intended to be a complete answer, but your second parameter's type looks wrong.

    Your DLL function: int _stdcall koduj (BSTR nr_id, int & x1) declares x1 as a reference to a (presumably) 32-bit integer.

    Your VBA declaration: Declare Function koduj Lib "<dll_directory_and_full_name>" (ByVal x As String, ByRef y As Integer) As Integer declares y as a pointer to a 16-bit integer.

    I'd suggest try changing VBA declaration as follows:

    Declare Function koduj _ Lib "<dll_directory_and_full_name>" (ByVal x As String, ByVal y As Long) As Long

    And, switching your DLL function signature to pass x1 by value:

    int _stdcall koduj (BSTR nr_id, int x1)

    0 讨论(0)
  • 2020-12-16 21:32

    Try declare a as long: Dim a As Long

    0 讨论(0)
  • 2020-12-16 21:33

    The reason is that even though VBA strings are internally UTF-16, VB always converts them to ASCII before talking to the outside world (Declared functions, file input/output). So when you Declare a parameter As String, VBA automatically converts the string and passes it out as ASCII. The matching parameter type on the C++ side should be LPSTR or LPCSTR.

    If you want to use BSTR on the C++ side, you need to also create an IDL file for that function, compile it into a TLB and reference the TLB from VBA, only then VBA will respect and use BSTR.

    Another problem is that C++'s int translates to VBA's Long.

    The reason why it works when called from Excel sheet is that apparently Excel ignores the VBA rules for string conversion. I believe this to be a bug.

    0 讨论(0)
  • 2020-12-16 21:35

    I'm guessing from the magnitude of the error that it's the numeric parameter that's going wrong - I would try more explicitly declaring the parameter type in your test VBA routine (probably Integer) and accepting it as that specific type on the C++ side (signed short, in that case).

    There's a great Microsoft article about all this at http://msdn.microsoft.com/en-us/library/office/bb687915(v=office.15).aspx.

    0 讨论(0)
提交回复
热议问题