接着上次的话题,这次来看一下一些简单对象的传递,这里所指的简单对象是指
C#
中的值类型,不包括
Struct
结构。关于结构的应用,我会在之后的专题中给出。为了讨论方便,我直接用
Native C++
编写要调用的
Dll
类。然后再用
C#
演示
P/Invoke
。
(
以下先给出
Native C++
的代码,记得要编译生成
Dll)
。
//// NativeDll.h ////
#ifdef NATIVEDLL_EXPORTS
#define NATIVE_API __declspec(dllexport)
#else
#define NATIVE_API __declspec(dllimport)
#endif
//// SimpleType.h ////
#pragma once
#include <iostream>
#include "NativeDll.h"
extern "C"
{
NATIVE_API void IntAsParamInput(int value);
NATIVE_API void IntAsParamOutput(int *pValue);
NATIVE_API void IntAsParamInAndOutput(int *pValue);
NATIVE_API int IntAsReturnValue();
}
//// SimpleType.cpp ////
#include "StdAfx.h"
#include "SimpleType.h"
using namespace std;
NATIVE_API void IntAsParamInput(int value)
{
cout << "The input value is " << value << endl;
}
NATIVE_API void IntAsParamOutput(int *pValue)
{
*pValue = 5;
cout << "The output value is " << *pValue << endl;
}
NATIVE_API void IntAsParamInAndOutput(int *pValue)
{
cout << "The input value is " << *pValue << endl;
*pValue = 15;
cout << "The output value is " << *pValue << endl;
}
NATIVE_API int IntAsReturnValue()
{
return 25;
}
在这些代码中,就一点解释一下,就是在
NativeDll.h
中的那一段宏,在编译生成
Dll
时,
NATIVEDLL_EXPORTS定义是默认的。所以就会将NATIVE_API展开为__declspec(dllexport)。在编译为Exe时候的情况正好是相反的,这样就可以直接引用该Dll的C++项目中,直接使用这里的.h文件了。
接着给出本次的
C#代码,其实也没啥困难的,就是在对应指针的地方使用out/ref就可以了,在C#中将引用传递与C++中的指针平行的对应起来应该还是比较好理解的。
using System;
using System.Runtime.InteropServices;
namespace PInvoke
{
static class StringResx
{
public const String DLL_PATH = @"......debugNativeDll.dll";
}
static class SimpleType
{
#region Extern Element
//NATIVE_API void IntAsParamInput(int value);
//NATIVE_API void IntAsParamOutput(int *pValue);
//NATIVE_API void IntAsParamInAndOutput(int *pValue);
//NATIVE_API int IntAsReturnValue();
[DllImport(StringResx.DLL_PATH, EntryPoint = "IntAsParamInput")]
static extern void IntAsParamInput(Int32 val);
[DllImport(StringResx.DLL_PATH, EntryPoint = "IntAsParamOutput")]
static extern void IntAsParamOutput(out Int32 val);
[DllImport(StringResx.DLL_PATH, EntryPoint = "IntAsParamInAndOutput")]
static extern void IntAsParamInAndOutput(ref Int32 val);
[DllImport(StringResx.DLL_PATH, EntryPoint = "IntAsReturnValue")]
static extern Int32 IntAsReturnValue();
#endregion
static public void TestFunction()
{
IntAsParamInput(56);
Int32 TestInt = 0;
IntAsParamOutput(out TestInt);
Console.WriteLine(TestInt);
TestInt = 8;
IntAsParamInAndOutput(ref TestInt);
Console.WriteLine(TestInt);
Console.WriteLine(IntAsReturnValue());
}
}
}
相关文章:
本文继续介绍C#中使用P/Invoke调用Unmanaged Code,重点展示了如何传递值类型参数,包括输入、输出和输入输出参数,并给出了C++编译的Dll代码示例以及C#调用的示例代码。
758

被折叠的 条评论
为什么被折叠?



