2014-03-12 139 views
0

我必须从C#中的DLL库访问一些函数。 我的第一步是创建一个包装类来解决它:我无法从另一个类访问包装类'方法

//Class TMDLLWrapper.cs 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Runtime.InteropServices; 

namespace TrueMarbleData 
{ 
    class TMDLLWrapper 
    { 

    [DllImport("TrueMarbleDLL.dll")] 
    public static extern int GetTileSize(out int width, out int height); 

    [DllImport("TrueMarbleDLL.dll")] 
    public static extern int GetNumTiles(int zoomLevel, out int numTilesX, out int numTilesY); 

    [DllImport("TrueMarbleDLL.dll")] 
    public static extern int GetTileImageAsRawJPG(int zoomLevel, int tileX, int tileY, out byte imageBuf, int bufSize, out int jpgSize); 
    } 


} 

然后,我创建了一个接口和一个类来访问包装类的方法:

//Interface ITMDataController.cs 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.ServiceModel; 

namespace TrueMarbleData 
{ 
    [ServiceContract] 
    public interface ITMDataController 
    {  
     [OperationContract] 
     int GetTileWidth(); 

     [OperationContract] 
     int GetTileHeight(); 

     [OperationContract] 
     int GetNumTilesAcross(int zoom); 

     [OperationContract] 
     int GetNumTilesDown(int zoom); 

     [OperationContract] 
     byte[] LoadTile(int zoom, int x, int y); 
    } 
} 


//Class TMDataControllerImpl.cs 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.ServiceModel; 
using TrueMarbleData; 

namespace TrueMarbleData 
{ 
    [ServiceBehavior(ConcurrencyMode=ConcurrencyMode.Multiple, 
         UseSynchronizationContext=false)] 
    internal class TMDataControllerImpl : ITMDataController 
    { 

      TMDLLWrapper obj = new TMDLLWrapper(); //Problem here: I cannot access 
                //wrapper class' methods 
                //Methods available: Equals, 
                //GetHashCode, GetType, ToString 
      public int GetTileWidth() 
      { 
       return 0; 
      } 

      public int GetTileHeight(); 

      public int GetNumTilesAcross(int zoom); 

      public int GetNumTilesDown(int zoom); 

      public byte[] LoadTile(int zoom, int x, int y); 
    } 
} 

我需要访问TMDataControllerImpl类中的“包装类”方法。但是,当我从TMDLLWrapper类创建一个对象时,我只能访问这些方法:Equals,GetHashCode,GetType,ToString。 这应该是一件容易的事情,我还没有弄清楚错误在哪里。 任何人都可以帮助我?

+0

你需要调用它的静态方法,而不是一个实例方法? – jparram

回答

0

internal默认。使包装类市民:

public class TMDLLWrapper 
{ 
... 
} 

然后,您可以访问它在一个静态的方式方法:

TMDLLWrapper.GetNumTiles(...); 
+0

It Works!谢谢! –

0

当您尝试存取权限的方法是这样的:

TMDLLWrapper obj = new TMDLLWrapper(); 

你只能访问实例的方法。所以,你应该用静态方法静态方法:

TMDLLWrapper.GetTileSize(a, b); 
+1

您不能从'extern'方法中删除'static',这些方法用于从非托管dll导入函数。 – Dennis

+0

好的,然后创建另一个不是静态的方法,并从那里调用它...我更新了答案。 Thanx –

0

由于TMDLLWrapper方法是静态的,你应该使用语法来访问静态方法:

TMDLLWrapper.GetTileSize(/* ... */);

你并不需要创建TMDLLWrapper的实例。此外,最好是使静态类:

static class TMDLLWrapper { /* ... */ }