如何将C#托管的结构传递给C ++非托管DLL并在结果中获取结构?

时间:2017-03-09 11:37:13

标签: c# c++ .net struct interop

我不太了解c ++,所以我添加了dll的所有代码。

C ++ ** ** Calculator.h

#ifndef CALCULATOR_H
#define CALCULATOR_H

#include "global.h"

struct CALCULATORSHARED_EXPORT Input {
    double a;
    double b;
};

struct CALCULATORSHARED_EXPORT Result {
    double sum;
    double diff;
    double prod;
    double div;
};

global.h

#ifndef CALCULATOR_GLOBAL_H
#define CALCULATOR_GLOBAL_H

#if defined(CALCULATOR_EXPORTS)
#  define CALCULATORSHARED_EXPORT __declspec(dllexport)
#else
#  define CALCULATORSHARED_EXPORT __declspec(dllimport)
#endif

#endif // CALCULATOR_GLOBAL_H

calculator.h

#include "calculator.h"

Result calculate( const Input& input) {
    Result result;

    result.sum = input.a + input.b;
    result.diff = input.a - input.b;
    result.prod = input.a * input.b;
    result.div = input.a / input.b;

    return result;
}

C#

[DllImport("Calculator.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern Result calculate(Input input);


        [StructLayout(LayoutKind.Sequential)]

        public struct Input
        {
            public double a;
            public double b;
        };

        [StructLayout(LayoutKind.Sequential)]

        public struct Result
        {            
            public double sum;
            public double diff;
            public double prod;
            public double div;
        };

        private void button1_Click(object sender, EventArgs e)
        {
            Input input;
            Result result;
            input.a = 5;
            input.b = 6;
            result = calculate(input);    
        }

我正在Unable to find an entry point named 'calculate' in DLL 'Calculator.dll'.

1 个答案:

答案 0 :(得分:1)

你必须这样做:

do {
        let data = try JSONSerialization.data(withJSONObject: yourArray)
        jsonString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as! String
    }
    catch {
    }

您无需在extern "C" { CALCULATORSHARED_EXPORT Result calculate(const Input& input) { } } CALCULATORSHARED_EXPORT两个结构上标记Input

Result否则函数的名称将被修改,extern "C"否则函数将不会被导出。

C#签名必须是:

CALCULATORSHARED_EXPORT

因为在C ++中它是public static extern Result calculate(ref Input input);

显然

Input&