Native C++ via CLR/C++到C#(二)

只说不练,假把式。

光说方法,不说代码也是伪教程。

从这篇开始,整理一些C#引用C++ DLL的具体方法。

基础类型的转换在baidu上搜索即可,

这里面关注一些类和STL的标准转化问题。

本文所有内容接在win7+vs2015下实现。

首先,C# List 和C++ std::vector之间的转化。

// This is the main DLL file.

#include "stdafx.h"

#include "CSample_CLR.h"

List^ CSample_CLR::Sample_CLR::Run(List^ list)
{
	std::vector vec;
	for (int i = 0; i< list->Count; i++)
	{
		vec.push_back(list[i]);
	}
	CCSample_CPP test;
	std::vector vec_result = test.convert(vec);
	_list = gcnew List();	
	for (int j = 0; j < vec_result.size(); j++)
	{
		_list->Add(vec_result[j]);
	}
	return _list;
}// CSample_CLR.h
#pragma once
#include "CSample_CPP.h"
#include   
#include   
#include   
using namespace System;
using namespace System::Collections;
using namespace System::Collections::Generic;
namespace CSample_CLR {

	public ref class Sample_CLR
	{
	public:
		List^ _list;
		List ^Run(List ^list);
	};
}
// symbol defined on the command line. This symbol should not be defined on any project
// that uses this DLL. This way any other project whose source files include this file see 
// CSAMPLE_CPP_API functions as being imported from a DLL, whereas this DLL sees symbols
// defined with this macro as being exported.
#ifdef CSAMPLE_CPP_EXPORTS
#define CSAMPLE_CPP_API __declspec(dllexport)
#else
#define CSAMPLE_CPP_API __declspec(dllimport)
#endif
#include 
// This class is exported from the CSample_CPP.dll
class CSAMPLE_CPP_API CCSample_CPP {
private:
	std::vector test;
public:
	CCSample_CPP(void);
	// TODO: add your methods here.
	std::vector convert(std::vector in_vector);
	
};#include "stdafx.h"
#include "CSample_CPP.h"
CCSample_CPP::CCSample_CPP()
{
    return;
}

std::vector CCSample_CPP::convert(std::vector in_vector)
{
	printf("%d\n", in_vector.size());
	test = in_vector;
	for (size_t i = 0; i < in_vector.size(); i++)
	{
		printf("%d\n", in_vector[i]);
	}
	return test;
}using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CSample_CLR;
namespace CSample
{
    class Program
    {
        static void Main(string[] args)
        {
            List list_test = new List();
            List list_result = new List();
            for (int i = 0; i < 10; ++i)
            {
                list_test.Add(i);
            }
            Sample_CLR test = new Sample_CLR();
            list_result = test.Run(list_test);
            for (int i = 0; i < 10; ++i)
            {
                Console.Write("{0}\n", list_result[i]);
            }
            Console.Read();

        }
    }
}

你可能感兴趣的:(算法研发)