How do I pass variable arguments from managed to unmanaged with a C++/CLI Wrapper?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-01 12:51:17

If you are really, really desperate then this is not impossible. A variadic function can only be called by C code and the call has to be generated by the C compiler. Let's take an example:

#include <stdarg.h>
#include <stdio.h>

#pragma unmanaged

void variadic(int n, ...) {
    va_list marker;
    va_start(marker, n);
    while (n--) {
        printf("%d\n", va_arg(marker, int));
    }
}

The compiler will turn a sample call like variadic(3, 1, 2, 3); into:

00D31045  push        3  
00D31047  push        2  
00D31049  push        1  
00D3104B  push        3  
00D3104D  call        variadic (0D31000h)  
00D31052  add         esp,10h  

Note how the arguments are passed on the stack, from left to right. The stack gets cleaned up after the call. You can emulate that exact same call pattern by using inline assembly. That looks like this:

void variadicAdapter(int n, int* args) {
    // store stack pointer so we can restore it
    int espsave;
    _asm mov espsave,esp;
    // push arguments
    for (int ix = n-1; ix >= 0; --ix) {
        int value = args[ix];
        _asm push value;
    }
    // make the call
    variadic(n);
    // fix stack pointer
    _asm mov esp,espsave;
}

Pretty straight forward, just some shenanigans to get the stack pointer restored. Now you have an adapter function that you can call from managed code. You'll need a pin_ptr<> to turn the array into a native pointer:

#pragma managed

using namespace System;

int main(array<System::String ^> ^args)
{
    array<int>^ arr = gcnew array<int>(3) { 1, 2, 3};
    pin_ptr<int> arrp(&arr[0]);
    variadicAdapter(arr->Length, arrp);
    return 0;
}

Works well and not actually that dangerous, tested in the optimized Release build. Beware that you have no hope of making this work if 64-bit code is required.

Steztric

The general recommendation is that it is not recommended: See this article

I would suggest using a std::vector<int> to store the arguments.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!