-1

I'm trying to create a Symlink Generator with c++/cli ( Windows based ) There is a Docu on Microsoft ( MS )

But i dont know excactly how it works.

I tryed to find a working excample, but i could not find one and i could not get a working solution on my own.

My Complete Code HERE!

private: System::Void btnCreateSymlinks_Click(System::Object^  sender, System::EventArgs^  e) {
  String^ pathSource = GetSourcePath();
  String^ pathDest = GetDestinationPath();
  String^ folder = System::IO::Path::GetFileName(pathSource);
  lblInfo->Text = pathSource + " -> " + pathDest + "" + folder;
}

How do i use the CreateSymbolicLink function with those pathSource and pathDest?

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
xQp
  • 302
  • 1
  • 5
  • 22

1 Answers1

2

In order to use .NET strings on the garbage collected stack, you'll need pinning pointers (this is something that p/invoke does automatically for C# coders, but C++/CLI coders need to request).

pin_ptr<const wchar_t> wcsTarget = PtrToStringChars(pathSource);
pin_ptr<const wchar_t> wcsSymlink = PtrToStringChars(Path::Combine(pathDest, folder));

Then just call the Unicode version of the API (since .NET strings are always Unicode).

CreateSymbolicLinkW(wcsSymlink, wcsTarget, 0U);
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • PtrToStringChars is not working with pin_ptr at least for me i dont know – xQp Dec 27 '16 at 16:08
  • i tryed a workaround with http://stackoverflow.com/questions/9782669/c-cli-system-string-to-mfc-lpctstr bit CreateSymbolicLinkW is not working – xQp Dec 27 '16 at 16:10
  • @xQp: Stay far away from MFC, and no reason to translate from Unicode to ANSI here, since the symlink API would just need to translate it back. If you don't have `#include` add it and try `PtrToStringChars` again. – Ben Voigt Dec 27 '16 at 16:11
  • Please explain "does not work". Is there a compile error? – Ben Voigt Dec 27 '16 at 16:16
  • It says: "_const_Char_ptr PtrToStringChars(_const_String_handle s) get ean interior gc pointer to the first character contained in a System::String object Error: A value of typ ""_const_Char_ptr"" can not be used to initialize an entity from Type ""cli::pin_ptr"" – xQp Dec 27 '16 at 16:22
  • @xQp: Sorry, forgot `const` in my example code. Please see my edit. – Ben Voigt Dec 27 '16 at 16:24
  • now its working but i made a mistake, it has not the same effect as MKLINK /d :/ – xQp Dec 27 '16 at 16:29
  • 1
    @xQp: Your question specifically passes a **filename**, not a directory. To make it work with directories, use the `SYMBOLIC_LINK_FLAG_DIRECTORY` flag as the third parameter. The documentation you linked explains that. – Ben Voigt Dec 27 '16 at 16:30
  • Thanks a lot ;) u r awesome – xQp Dec 27 '16 at 16:36