2012-05-29 30 views
0

我需要在使用phalanger以php編寫的純編譯dll中嵌入一些資源。 這些是我在Visual Studio中設置爲「Embedded Resource」的txt文件。在Phalanger中使用System.Reflection和資源

我的問題是我不能使用Assembly類來獲取使用GetManifestResourceStream的資源。

我想這樣的代碼: 使用SYSTEM \反射\大會

$asm = Assembly::GetExecutingAssembly(); //this gives me mscorlib instead of my dll 
$str = $asm->GetManifestResourceStream("name"); 

我的問題是:我怎麼去嵌入資源phalanger訪問? 非常感謝

回答

0

我不確定,爲什麼Assembly :: GetExecutingAssembly()返回一個不正確的值。反正要解決的$ ASM值,可以使用下面的代碼:當你發佈

$asm->GetManifestResourceStream("TextFile1.txt"); 

$MyType = CLRTypeOf MyProgram; 
$asm = $MyType->Assembly; 

然後你就可以訪問嵌入資源,也可以包括標準的資源文件(的.resx)到您的項目,並使用\ SYSTEM \資源\ ResourceManager的

只要注意,目前可以有Phalanger項目中只有一個的.resx

+0

非常感謝,第一個解決方案效果很好!不幸的是,如果我使用流讀取器將文本文件讀取爲字符串(使用ReadToEnd()),在獲取真實文件內容之前,我會獲取大量未知字節,還有一些文本顯示「System.Resources.ResourceReader ...」 」。我在c#ad中編寫了相同的代碼,只有文件ccontent符合預期。 – user1423242

0

這個問題是舊的,但負責這個問題的Phalanger代碼(Php.Core.Emit.AddResourceFile()方法)的一部分並沒有改變,因爲這是問。我遇到了同樣的問題,並且以(幾乎)非破解的方式解決了這個問題。您必須提供替代名稱(/res:/path/to/filename,alternative-name)才能使其工作。

$asm = clr_typeof('self')->Assembly; 
$resourceStream = $asm->GetManifestResourceStream("filename"); 
$reader = new \System\Resources\ResourceReader($resourceStream); 

$type = $data = null; 
$reader->GetResourceData("alternative-name", $type, $data); 

// and still there are 4 excess bytes 
// representing the length of the resource 
$data = \substr($data, 4); 
$stream = new IO\MemoryStream($data); 

// after this $stream is usable as you would expect 

直白GetManifestResourceStream()(由的Jakub的建議)不起作用,因爲Phalanger不使用System.Reflection.Emit.ModuleBuilder.DefineManifestResource()(就像我認爲它應該當無法識別的文件格式提供)。它使用ModuleBuilder.DefineResource(),它返回ResourceWriter,而不是僅適用於.resources文件。當你需要閱讀你的資源時,這就是要求使用ResourceReader的要求。

注意:這個答案適用於Phalanger master branch at the time of writing和以前的版本,因爲大約2011年指出,由於它看起來像一個bug(尤其是需要同時使用原始的和替代名稱)。