调用与可变数量的从非托管code参数的.NET函数函数、数量、参数、code

2023-09-06 07:39:49 作者:恋恋会不舍

我想调用C#函数与可变数量的参数:

I would like to call C# function with variable number of parameters:

void f1(object arg1, params object[] argsRest);

从非托管,C函数变量参数包装F1。

from unmanaged, C function with variable parameters that wraps f1.

这又如何achived?

How can this be achived?

推荐答案

要暴露你的管理功能,您将需要编写一个混合模式DLL,它充当网桥(你应该阅读的 MSDN上这个的文章作为背景。)

To expose your managed function you will need to write a mixed mode DLL that acts as a bridge (You should read this article on MSDN as background.)

您C ++ - CLI桥DLL包含code类似于以下...

Your c++-cli bridge DLL will contain code similar to the following ...

#include <cstdarg>

extern "C" {
    __declspec(dllexport) void f1wrapper(void *arg1, int nargs, ...)
    {
        array<Object^>^ managedArgs = gcnew array<Object^>(nargs);
        va_list args;
        va_start(args, nargs);
        for (int _i = 0; _i < nargs; ++_i)
        {
            managedArgs[_i] = ???; // <- you need to translate args
        }
        va_end(args);

        // Call your function
        Object^ managedArg1 = ???; // <- translate arg1
        f1(managedArg1, managedArgs);
    }
}

您再链接对混合模式的DLL和调用f1wrapper(...)从C code。不完整的,而应该提供足够的基础,为您进行试验。

You then link against the mixed mode DLL and call f1wrapper(...) from your C code. Not complete, but should provide enough foundation for you to experiment.