C++ builder XE动态链接库中使用STL::vector

一.建立dll
菜单File --> New -->Other,弹出New Items 窗体,选择New页的DLL Wizard,点击OK.
弹出DLL Wizard窗体,默认选项即可(C++选中,Use VCL选中,Multi Threaded为灰色不可用)
点击OK.

在代码窗体中输入如下内容:

// ---------------------------------------------------------------------------

#include <vcl.h>
#include <vector>
#include <windows.h>
#pragma hdrstop
// ---------------------------------------------------------------------------
// dll函数的外部接口

//std::vector<int>函数的返回值 

//pv (std::vector<int>v)为函数名和函数的参数
extern "C" __declspec(dllexport) std::vector<int>__stdcall pv
 (std::vector<int>v);
#pragma argsused

int WINAPI DllEntryPoint(HINSTANCE hinst, unsigned long reason,
 void* lpReserved) {
 return 1;
}

// ---------------------------------------------------------------------------
// dll函数的实现--

std::vector<int>__stdcall pv(std::vector<int>v) {
 if (v.size() > 0) {
  v.clear();
 }
 for (int i = 0; i < 10; i++) {
  v.push_back(i);
 }
 return v;
}


建立一个应用程序,在窗体上1个Button,2个Edit控件.
要实现在Edit1里输入一个数字,点击button按钮,调用dll的函数后,将返回值返回到Edit2控件中.
首先保存项目,之后把上面编译后的Project1.dll拷贝到现在的目录.
双击button1控件,在代码窗体中输入如下代码:

// ---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop
#include <vector>

#include <stdio.h>
#include "Unit1.h"
// ---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;

// ---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) {
}

// ---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender) {
 std::vector<int>v;

 HINSTANCE ins;

 String dllfn = "Project1.dll";
 // wchar_t *tmp=dllfn.w_str();
 LPCTSTR tmp = dllfn.w_str(); // 这样是解决Unicode字符匹配问题
 ins = ::LoadLibrary(tmp);
 if (ins == NULL) {
  throw "Can't load library!";
 }
 else {
  std::vector<int>(__stdcall *p)(std::vector<int>); // 定义数据类型
  p = (std::vector<int>__stdcall(*)(std::vector<int>))::GetProcAddress
   (ins, "pv");
  if (p == NULL) {
   FreeLibrary(ins);
   throw "Can't Load Address!";
  }
  else {
   v = p(v);
   Edit1->Text = v[0];
   Edit2->Text = v[9];
  }
 }
 if (!FreeLibrary(ins)) {
  throw "Can't Free!";
 }
}
// ---------------------------------------------------------------------------

你可能感兴趣的:(C++,vector,dll,button,wizard,winapi)