创建和使用托管程序集(C++)

时间:2022-08-28 03:00:44

官网实例

托管程序集是一种库,您可以创建该库以便高效地重用代码。 这样,就不必在多个程序中重新实现同样的例程,而只需编写这些例程一次,然后在需要该功能的应用程序中引用它们即可。

创建类库项目MathAssembly

1.VC++,CLR-->类库,MathAssembly。 2.向类库添加类MyMath
// MathAssembly.h
#pragma once
using namespace System;
namespace MathAssembly
{
public ref class MyMath
{
public:
static double Add(double a,double b);
static double Sub(double a,double b);
static double Mul(double a,double b);
static double Div(double a,double b);
};
}

// MathAssembly.cpp 这是主 DLL 文件。#include "stdafx.h"#include "MathAssembly.h"namespace MathAssembly{double MyMath::Add(double a,double b){return a+b;}double MyMath::Sub(double a,double b){return a-b;}double MyMath::Mul(double a,double b){return a*b;}double MyMath::Div(double a,double b){if (b == 0){throw gcnew DivideByZeroException("b connot be zero!");}return a/b;}}

编译生成了MathAssembly.dll文件,供useMathAssembly引用

创建引用类库的应用程序UseMathAssembly

1.VC,CLR-->CLR 控制台应用程序: UseMathAssembly 2.右击项目,引用-->添加新引用:MathAssembly 3.使用代码
// UseMathAssembly.cpp: 主项目文件。#include "stdafx.h"using namespace System;int main(array<System::String ^> ^args){    Console::WriteLine(L"Hello World");double a=7.4;int b=99;Console::WriteLine("a + b ={0}",MathAssembly::MyMath::Add(a,b));Console::WriteLine("a - b ={0}",MathAssembly::MyMath::Sub(a,b));Console::WriteLine("a * b ={0}",MathAssembly::MyMath::Mul(a,b));Console::WriteLine("a / b ={0}",MathAssembly::MyMath::Div(a,b));    return 0;}