Vous êtes sur la page 1sur 11

4/24/2015

CreatingaManagedWrapperforaLibFileTomsBlog

TomsBlog
December11,2008
CreatingaManagedWrapperforaLibFile
Filedunder:General.NETTomShelton@12:51pm
So,youhavealibfileanditscorrespondingheaderfile,andyouneedtouseitfromyourmanagedapplication.Nowwhat?Well,the
simplestansweristocreateaC++/CLRwrapperDLLtoexposethefunctionalityyouneed.Heresastepbystepwalkthroughofthe
process.

1.

Thefirststepinthiswalkthroughistocreatelibfilethatwewanttoexposeinourmanagedcode.Todothis,createablankVisual
StudioSolutionandgiveitaname.

2.

Oncewehaveasolution,letsaddaC++staticlibraryprojecttothesolution.Todothis,gotoSolutionExplorerandrightclickonthe
solution.Onthecontextmenu,selectAdd>NewProject.ThisshouldbringuptheAddNewProjectdialog.AddanewC++
Win32project.Giveitaname,andselectOK.

http://tomshelton.net/index.php/2008/12/11/creatingamanagedwrapperforalibfile/

1/11

4/24/2015

CreatingaManagedWrapperforaLibFileTomsBlog

3.

WhentheWin32ApplicationWizardcomesup,selecttheNextbutton.UnderApplicationType,selectStaticLibrary.Also,for
thisexampleIturnedoffPrecompiledheader.AndselectFinish.

4.

GototheSolutionExploreragain,andrightclickonyourstaticlibraryproject,andselectAdd>Class.Thiswillbringupthe

http://tomshelton.net/index.php/2008/12/11/creatingamanagedwrapperforalibfile/

2/11

4/24/2015

CreatingaManagedWrapperforaLibFileTomsBlog

AddClassdialog,selectAdd.

5.

FillintheinformationintheGenericC++ClassWizard.SelectFinish.

http://tomshelton.net/index.php/2008/12/11/creatingamanagedwrapperforalibfile/

3/11

4/24/2015

CreatingaManagedWrapperforaLibFileTomsBlog

6.

ModifytheresultingAddClass.hfiletolooklikethis:

1:#pragmaonce
2:
3:namespaceAddTwoNumbersLib
4:{
5:classAddClass
6:{
7:public:
8:staticdoubleAdd(doublex,doubley);
9:};
10:}

7.

LetsprovidetheimplementationinAddClass.cpp:

1:#include"AddClass.h"
2:
3:namespaceAddTwoNumbersLib
4:{
5:doubleAddClass::Add(doublex,doubley)
6:{
7:returnx+y;
8:}
9:}

Atthispoint,youshouldbeabletosuccessfullycompileourexamplelibfile.

8.

OKwearenowsetupfortherestofthisexample.Wehavealibfileandaheaderfilethatwewillexposetoourmanaged
application.Todothis,wewillcreateanewCLRclasslibrary,usingC++/CLI.So,gobacktotheSolutionExplorerandrightclickon
thesolution.SelectAdd>NewProject.IntheProjectTypestreeview,selectVisualC++>CLR.IntheTemplatespane,
selectClassLibrary,andgiveitanameandselectOK.

http://tomshelton.net/index.php/2008/12/11/creatingamanagedwrapperforalibfile/

4/11

4/24/2015

CreatingaManagedWrapperforaLibFileTomsBlog

9.

Nowweneedtosetacoupleofprojectpropertiestobeabletousethelibfile.So,inSolutionExplorer,rightclickontheClrWrapper
projectandselectProperties.IntheClrWrapperPropertyPages,selectAllConfigurationsintheConfigurationdropdown.Then,
selectConfigurationProperties>C/C++>General.ModifytheAdditionalIncludeDirectoriesproperty,topointtothedirectory
containingtheheaderfileforthe.lib.

http://tomshelton.net/index.php/2008/12/11/creatingamanagedwrapperforalibfile/

5/11

4/24/2015

CreatingaManagedWrapperforaLibFileTomsBlog

SelectingthebrowsebuttonwillbringuptheAdditionalIncludeDirectoriesdialog.

http://tomshelton.net/index.php/2008/12/11/creatingamanagedwrapperforalibfile/

6/11

4/24/2015

CreatingaManagedWrapperforaLibFileTomsBlog

Clickinginthelistatthetop,willagaingiveyouabrowsebuttonthatwillbringupafolderbrowserdialog.Usethefolderbrowserto
pointtothedirectorywhereyourlibfilesheaderisin.

SelectOK,thenApplyintheClrWrapperPropertyPages.

10. Now,weneedtotellthelinkerwherethelibfileis.WecoulddothisbyaddingaprojectreferencetotheAddTwoNumbersLibproject
but,sincewearetryingtosimulateusonlyhavingthelib,welldoitthehardway!
WiththeClrWrapperPropertyPagesdialogstillopen,ConfigurationProperties>Linker>Input.

http://tomshelton.net/index.php/2008/12/11/creatingamanagedwrapperforalibfile/

7/11

4/24/2015

CreatingaManagedWrapperforaLibFileTomsBlog

Select,AdditionalDependenciesandthenthebrowsebuttonthatappears.ThiswillbringuptheAdditionalDependenciesdialog.

Inthelistatthetop,insertthefullpathtothelibfile(makesureitsinquotes).

SelectOK.AndOKagainontheClrWrapperPropertyPages.

11. Now,letscreateourwrapper.Modifythefollowingfiles
http://tomshelton.net/index.php/2008/12/11/creatingamanagedwrapperforalibfile/

8/11

4/24/2015

CreatingaManagedWrapperforaLibFileTomsBlog

stdafx.h

1://stdafx.h:includefileforstandardsystemincludefiles,
2://orprojectspecificincludefilesthatareusedfrequently,
3://butarechangedinfrequently
4:
5:#pragmaonce
6:
7:#include"AddClass.h"

ClrWrapper.h
1://ClrWrapper.h
2:
3:#pragmaonce
4:
5:usingnamespaceSystem;
6:
7:namespaceClrWrapper{
8:
9:publicrefclassAddClass
10:{
11:public:
12:doubleAdd(doublex,doubley);
13:};
14:}

ClrWrapper.cpp
1://ThisisthemainDLLfile.
2:
3:#include"stdafx.h"
4:
5:#include"ClrWrapper.h"
6:usingnamespaceClrWrapper;
7:
8:doubleAddClass::Add(doublex,doubley)
9:{
10:returnAddTwoNumbersLib::AddClass::Add(x,y);
11:}

Withthatdone,youshouldbeabletocompilethesolution.

12. Now,createamanagedprojectinthelanguageofyourchoiceC#orVB,andaddareferencetoyourtheClrWrapper.dll.Oncedone,
youshouldbeabletowrite,compile,andruncodelikethefollowing:

C#
1:usingSystem;
2:usingClrWrapper;
3:
4:namespaceCSharpClient
5:{
6:classProgram
7:{
8:staticvoidMain(string[]args)
9:{
10:AddClassaddClass=newAddClass();
11:
12:Console.WriteLine(addClass.Add(1,2));
13:Console.WriteLine(addClass.Add(2,2));
14:Console.WriteLine(addClass.Add(649,1));
15:}
16:}
17:}

VB

http://tomshelton.net/index.php/2008/12/11/creatingamanagedwrapperforalibfile/

9/11

4/24/2015

CreatingaManagedWrapperforaLibFileTomsBlog

1:OptionExplicitOn
2:OptionStrictOn
3:
4:ImportsSystem
5:ImportsClrWrapper
6:
7:ModuleProgram
8:
9:SubMain()
10:DimaAsNewAddClass()
11:
12:Console.WriteLine(a.Add(1,2))
13:Console.WriteLine(a.Add(2,2))
14:Console.WriteLine(a.Add(649,1))
15:EndSub
16:
17:EndModule

Hopefully,someonewillfindthisuseful.
Comments(6)

6Comments
1.
Excellent!!!Itsurelyworkedforme!
CommentbyDanielDecember7,2009@1:14pm
2.
Hi,
Wewouldliketolaunchfewflashbasedapplication(Presentationwithswforexe)Anyideahowthiswrappercanhelp?
CommentbyHarishMarch10,2010@2:36am
3.
Hi,Ihavea.libfileanditscorresponding.hfile(fromathirdpartydeveloperandIdonthavethesourcecode).Iwanttousethemin
c#application.Itriedthemethodyoutalkedaboutinthispage.IfIcreatealibfileasyousaidinthisarticle,everythingworksfine
andIcanworkwiththeclassandmethodsinsidethelibrary.butwhenIreplacemylibrarywiththemainlibrarythatIwanttowork
with,Igetthiserror:
Error1errorC2059:syntaxerror:__declspec(dllimport).Idontknowanythingaboutc++anddonthaveaccesstoanyonewho
knowsitnow.
CommentbySaharJuly20,2010@2:06pm
4.
Ireally,reallywanttothankyou,TomShelton!FromprobablyaweekImtryingtodoexactlythesameandthisisthefirsttutorial
thatissodetailedandhelpful!Thanksagain!!!
CommentbyEvgeniKrustevSeptember14,2010@4:51pm
5.
Thankssomuchforthis,itwasveryhelpful.ExactlywhatIneeded.
CommentbyAndyJanuary28,2014@3:09pm
6.
http://tomshelton.net/index.php/2008/12/11/creatingamanagedwrapperforalibfile/

10/11

4/24/2015

CreatingaManagedWrapperforaLibFileTomsBlog

Thanksawholebunch.Thishassavedmehoursofunnecessarywork.
CommentbyAnonMarch18,2014@7:18am
RSSfeedforcommentsonthispost.TrackBackURL

Leaveacomment
Name(required)
Mail(willnotbepublished)(required)
Website

SubmitComment

Blogroll
WhatIFoundOut
Categories:
.NET
C#
ADO.NET
P/Invoke
General.NET
VisualBasic
General
P/Invoke
Uncategorized
Search:
Search

Archives:
January2010
October2009
August2009
May2009
February2009
January2009
December2008
November2008
October2008
Meta:
Login
RSS
CommentsRSS
ValidXHTML
XFN
WP
PoweredbyWordPress

http://tomshelton.net/index.php/2008/12/11/creatingamanagedwrapperforalibfile/

11/11

Vous aimerez peut-être aussi